KatInterview

Function Composition Twice and Core Container Cost Comparison

Data Structure DesignModel answer
MediumModel answerData Structure Designhigher-order-functionsclosuresside-effects

Last updated

Write a helper that feeds a function's output back into itself, explain closures and side effects, then compare arrays, linked lists, stacks and queues by operation cost.

This question has two parts, both answered in prose and code. No automatic judge is involved, so clarity and precision matter.

Part 1: Functions as values

Write a helper, in any language you like, called applyTwice(f, x). It takes a function f and a value x, and returns the result of calling f on the result of calling f on x.

In your answer:

  • Show how a function (or delegate, lambda, or functor) is passed as an argument in your chosen language.
  • Explain what a closure is and give a short example where the function you pass captures a variable from its surrounding scope.
  • Discuss side effects. What happens if f prints, mutates its argument, or updates a counter, given that f runs twice?
  • State any type requirement that f must satisfy for the double call to make sense.

Part 2: Container cost model

Analyze these four structures:

  • Array (dynamic/resizable)
  • Linked list
  • Stack
  • Queue

For each, give time and space complexity for insert, delete, search, and iteration. Then explain in which situations you would pick each one over the others.

State your assumptions clearly, for example whether the linked list is singly or doubly linked, whether it keeps a tail pointer, and what backs your stack and queue.

Hints

Hint 1

For the double call, evaluate the inner call first and store or pass its result straight into the outer call. Think about what type the first call must return for the second call to be legal.

Hint 2

A closure keeps a variable alive after the function that created it has returned. Try a function factory that returns an 'add n' function, and think about what goes wrong if captured variables are rebound in a loop.

Hint 3

For the container comparison, separate the cost of locating a position from the cost of the actual insert or delete. Linked list operations are only constant time if you already hold a reference to the node.

Hint 4

Stacks and queues are interfaces (LIFO and FIFO), not storage layouts. Decide what backs each one, and watch for the trap of removing from the front of a plain dynamic array.