Function Composition Twice and Core Container Cost Comparison
Data Structure DesignModel answerLast 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
fprints, mutates its argument, or updates a counter, given thatfruns twice? - State any type requirement that
fmust 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Applying a function twice
Approach
Functions are first-class values in most modern languages, so they can be passed, returned, and stored. applyTwice evaluates the inner call, then feeds its result to the outer call. Arguments are evaluated eagerly, so the order is fixed: the inner call (and its side effects) happens before the outer one.
from typing import Callable, TypeVar
T = TypeVar("T")
def apply_twice(f: Callable[[T], T], x: T) -> T:
if not callable(f):
raise TypeError("f must be callable")
return f(f(x))
def make_adder(n):
def add(x):
return x + n # n is captured from the enclosing scope
return add
apply_twice(make_adder(5), 10) # 20
Equivalents elsewhere: Function<T,T> in Java, Func<T,T> in C#, and a template parameter or std::function<T(T)> in C++.
Type requirement
For f(f(x)) to be valid, the output type of f must be acceptable as its input. In a typed language this means f: T -> T. A function like len applied to a string fails on the second call because it returns an integer.
Closures
A closure is a function bundled with the variables it captured from its defining scope. make_adder(5) returns a function that still remembers n = 5 after make_adder has returned.
Common pitfalls:
- Late binding. Closures capture variables, not values. In
[lambda x: x + i for i in range(3)]every lambda sees the finali. Fix it by binding at definition time (lambda x, i=i: x + i) or by using a factory function. - Rebinding captured state. In Python the inner function needs
nonlocalto reassign a captured variable. Mutating a captured list or dict does not need it.
Side effects
f runs exactly twice, so any side effect also happens twice: a print appears twice, a counter increases by two, a network call is made twice. If f mutates its argument (for example lst.append(1)), the caller's object is changed twice. A pure f makes the result depend only on x, which is easy to test and reason about. If f is impure, document it or make a copy first.
Edge cases
fis not callable: raise a clear error.fthrows on the first call: the second call never happens.- Output type does not match input type: the second call fails.
- Generalization
apply_n(f, x, n): withn = 0it returnsx, the identity.
Complexity
Time is two times the cost of f plus O(1) overhead. Extra space is O(1) beyond what f allocates.
Part 2: Container comparison
Assumptions: dynamic array (like Python list), doubly linked list with head and tail pointers, stack backed by a dynamic array, queue backed by a deque or ring buffer.
| Operation | Dynamic array | Linked list | Stack | Queue |
|---|---|---|---|---|
| Access by index | O(1) | O(n) | top only, O(1) | front only, O(1) |
| Insert at end | O(1) amortized | O(1) with tail | push O(1) amortized | enqueue O(1) |
| Insert at front/middle | O(n) shift | O(1) given the node; O(n) to find it | n/a | n/a |
| Delete at end | O(1) | O(1) doubly; O(n) singly | pop O(1) | n/a |
| Delete at front/middle | O(n) shift | O(1) given the node; O(n) to find it | n/a | dequeue O(1) |
| Search by value | O(n); O(log n) if sorted | O(n) | O(n) | O(n) |
| Iteration | O(n), cache-friendly | O(n), pointer chasing | O(n) | O(n) |
| Space | O(n) plus spare capacity | O(n) plus 1 to 2 pointers per node | O(n) | O(n) |
Notes
- Amortized append. Arrays grow geometrically, so the occasional O(n) resize averages out to O(1) per append.
- "O(1) linked list" needs a handle. Insert and delete are constant time only if you already have the node. Finding it is O(n). Interviewers often probe this.
- Queue trap. Removing from the front of a plain array (
list.pop(0)) costs O(n). Use a deque or circular buffer. - ADT versus implementation. Stack and queue are defined by behavior (LIFO and FIFO). Either an array or a linked list can implement them.
- Constants matter. Arrays store data contiguously and benefit from CPU caches, so for equal big-O they usually beat linked lists in practice. Linked list nodes also pay per-node allocation and pointer overhead.
When to choose each
- Array: random access, mostly appends, fast scans, sorting, binary search. This is the sensible default.
- Linked list: frequent insertion and removal at known positions with no indexing, such as an LRU cache (hash map plus doubly linked list) or splicing lists. Accept worse locality.
- Stack: undo history, depth-first search, expression evaluation, bracket matching, simulating recursion.
- Queue: breadth-first search, task scheduling, producer/consumer buffers, rate limiting.
Common mistakes
- Claiming linked list insertion is O(1) without mentioning the search cost.
- Forgetting that array insertion in the middle shifts elements.
- Treating stack and queue as separate storage layouts instead of interfaces.
- Using a late-bound loop variable in a closure and being surprised by the result.
- Ignoring that
applyTwicedoubles side effects.
Short stack and queue sketch
from collections import deque
class Stack:
def __init__(self): self._a = []
def push(self, v): self._a.append(v)
def pop(self):
if not self._a: raise IndexError("empty")
return self._a.pop()
class Queue:
def __init__(self): self._d = deque()
def enqueue(self, v): self._d.append(v)
def dequeue(self):
if not self._d: raise IndexError("empty")
return self._d.popleft()
Both give O(1) for their core operations, which is the main point to demonstrate.