Repeated Function Application and Core Data Structure Complexity

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement two higher-order utilities in Python that repeatedly feed a value through a unary callable:

  1. apply_twice(f: Callable[[T], T], x: T) -> T

    • Evaluates f(x) first, then passes that return value into f a second time and returns f(f(x)).
    • f may be any Python callable: a def function, a lambda, a lexical closure, a built-in function, a bound or unbound method, a functools.partial wrapper, or an instance of a class defining __call__.
    • Raises TypeError if f is not callable.
  2. apply_n(f: Callable[[T], T], x: T, n: int) -> T

    • Applies f sequentially n times starting from x. When n == 0, returns x directly without invoking f. When n >= 1, invokes f on the running value n times in order so any stateful callable observes n distinct calls.
    • Raises TypeError if f is not callable (even when n == 0).
    • Raises TypeError if n is not an int or if n is a bool (True or False).
    • Raises ValueError if n < 0.
    • Must execute iteratively in O(1) auxiliary stack space so large iteration counts (such as n = 100_000) do not trigger a RecursionError.

Alongside the implementation, be ready to discuss how callables, lexical closures, and mutable side effects behave across repeated invocations, as well as the asymptotic time and space trade-offs of dynamic arrays, singly and doubly linked lists, stacks, and queues across insertion, deletion, search, and full traversal.

Examples

Example 1

Input:

a = apply_twice(lambda v: 3 * v - 2, 4)
b = apply_twice(lambda s: "[" + s + "]", "tag")

Output:

a == 28
b == "[[tag]]"

Explanation: For a, the first call computes 3 * 4 - 2 = 10, and the second call feeds 10 back in to compute 3 * 10 - 2 = 28. For b, "tag" becomes "[tag]" on the first pass and "[[tag]]" on the second pass.

Example 2

Input:

def make_shifter(step: int):
    return lambda v: v + step

c = apply_twice(make_shifter(7), 2)
d = apply_n(lambda v: v * 3, 2, 4)
e = apply_n(lambda v: v * 3, 99, 0)

Output:

c == 16
d == 162
e == 99

Explanation: make_shifter(7) returns a closure retaining step = 7, advancing 2 -> 9 -> 16. Calling apply_n with n = 4 triples 2 four times (2 -> 6 -> 18 -> 54 -> 162), while n = 0 returns 99 without calling f.

Constraints

  • f must accept its own return type (Callable[[T], T]); non-callable f values must raise TypeError.
  • 0 <= n <= 100_000 for valid apply_n calls (n < 0 raises ValueError; non-integer or boolean n raises TypeError).
  • Valid falsy data values (0, None, "", []) must pass through f unmodified by truthiness checks.
  • Auxiliary call-stack space in apply_twice and apply_n must be O(1) beyond the memory used by f itself.

Step-by-step walkthrough

  1. Understand the goal and the type contract

    This problem combines two core software-engineering fundamentals:

    1. Higher-order functions and state: Implement apply_twice(f, x) to compute f(f(x)), generalize it iteratively to apply_n(f, x, n) for n sequential applications, and explain how callable values, closures, and side effects interact.
    2. Data-structure trade-offs: Compare dynamic arrays, linked lists, stacks, and queues across insert, delete, search, and traversal (time and space), and explain when to choose each one.

    Start by picturing apply_twice(f, x) as a two-stage pipeline where the output of the first call becomes the input of the second call:

    x  ---[ call f ]--->  first_result = f(x)  ---[ call f ]--->  second_result = f(first_result)
    4  ---[ 3v - 2 ]--->  10                   ---[ 3v - 2 ]--->  28
    

    Notice the immediate type rule: because f must consume its own return value on the second step, f's output type must be valid as f's input type (Callable[[T], T]). Passing len with "abc" works once (len("abc") -> 3), then crashes on the second step (len(3) raises TypeError).

  2. Passing functions (and delegates) as values

    In Python, functions are first-class objects (values that can be stored in variables, kept in lists, passed as arguments, and returned from other functions). A function like apply_twice that accepts or returns another function is called a higher-order function.

    Unpacking the two calls into named variables makes the data flow crystal clear and easy to step through in a debugger:

    from typing import Callable, TypeVar
    
    T = TypeVar("T")
    
    
    def apply_twice(f: Callable[[T], T], x: T) -> T:
        """Return f(f(x)): call f on x, then call f on that result."""
        # Validate upfront so non-callable inputs fail with a clear error message.
        if not callable(f):
            raise TypeError(f"f must be callable, got {type(f).__name__}")
    
        # Phase 1: run f on the initial input x.
        first_result = f(x)
        # Phase 2: feed that output right back into f as its next input.
        second_result = f(first_result)
        return second_result
    

    Any Python callable works automatically: a def function, a lambda, a built-in like abs, a bound method like "-".join, a functools.partial, or an instance of a class defining __call__. Other mainstream languages express the exact same pattern using their own callable types:

    Python:      apply_twice(lambda v: 3 * v - 2, 4)               # 28 (any callable object)
    Java:        <T> T applyTwice(UnaryOperator<T> f, T x)         // functional interface: f.apply(f.apply(x))
    C#:          T ApplyTwice<T>(Func<T, T> f, T x) => f(f(x));    // delegate: type-safe method reference
    JavaScript:  const applyTwice = (f, x) => f(f(x));             // first-class function value
    C / C++:     int apply_twice(int (*f)(int), int x)             // raw function pointer (or std::function)
    
  3. Generalizing to n applications iteratively

    Interviewers frequently ask right away: "What if we want to apply f n times?" Applying f zero times (n = 0) leaves x unchanged (the mathematical identity f^0(x) = x), while n < 0 has no general meaning because an arbitrary black-box function f has no inverse.

    A recursive solution (return x if n == 0 else f(apply_n(f, x, n - 1))) looks tidy, but each recursive call pushes a frame onto the call stack (O(n) extra memory) and crashes with RecursionError around n = 1,000 in standard Python. A simple for loop updates one variable in O(1) extra memory even when n = 100,000:

    def apply_n(f: Callable[[T], T], x: T, n: int) -> T:
        """Return f applied n times to x; apply_n(f, x, 0) == x."""
        # Check callable(f) even when n == 0 so invalid callables never slip through silently.
        if not callable(f):
            raise TypeError(f"f must be callable, got {type(f).__name__}")
        # Reject booleans explicitly because bool is a subclass of int in Python (True == 1).
        if isinstance(n, bool) or not isinstance(n, int):
            raise TypeError(f"n must be an int, got {type(n).__name__}")
        if n < 0:
            raise ValueError("n must be non-negative")
    
        # current holds the running value after each application (starts at x for n == 0).
        current = x
        # Use an iterative loop instead of recursion so large n (e.g. 100_000) uses O(1) space
        # and never hits Python's ~1000-frame recursion limit.
        for _ in range(n):
            current = f(current)
        return current
    
  4. Closures: functions that carry an environment

    A closure is an inner function bundled together with references to variables from the enclosing scope where it was created, keeping those variables alive even after the outer function has returned:

    def make_adder(k: int) -> Callable[[int], int]:
        """Return a pure closure that remembers outer variable k after make_adder returns."""
        def add(v: int) -> int:
            return v + k
        return add
    

    When add7 = make_adder(7) runs, add7 holds a hidden cell pointing to k = 7, so apply_twice(add7, 2) computes 2 -> 9 -> 16.

    The classic closure interview trap (late binding): Python closures capture the variable box, not a snapshot of its value at the moment the lambda was created. Creating functions inside a for loop makes every function share the exact same loop variable i:

    # Buggy: all three lambdas look up the same variable `i` when called later (after i == 2)
    buggy = [lambda v: v + i for i in range(3)]
    # apply_twice(buggy[0], 0) -> 0 + 2 = 2 -> 2 + 2 = 4 (NOT 0!)
    
    # Fix: bind the current value of `i` as a default parameter at creation time
    fixed = [lambda v, step=i: v + step for i in range(3)]
    # apply_twice(fixed[0], 0) -> 0 + 0 = 0
    

    (By contrast, Java requires captured local variables in lambdas to be effectively final—never reassigned—preventing this loop bug at compile time.)

  5. Side effects and mutable state

    A pure function computes its return value solely from its arguments and modifies nothing outside itself (add7 above is pure). A side effect is any observable change outside the return value: mutating a captured variable, mutating an input list/dict in place, writing to a database, or charging a credit card.

    Because apply_twice invokes f two separate times, every side effect happens twice:

    def make_call_counter() -> Callable[[int], int]:
        """Return a stateful closure whose call count mutates on every invocation."""
        # calls: integer counter stored in the enclosing scope cell shared across calls.
        calls = 0
    
        def double_and_count(v: int) -> int:
            # nonlocal lets the inner function rebind `calls` in make_call_counter's scope.
            nonlocal calls
            calls += 1
            return v * 2
    
        return double_and_count
    

    Highlight three practical side-effect consequences in an interview: - Stateful closures (nonlocal): Calling apply_twice(make_call_counter(), 3) increments calls from 0 -> 1 -> 2 while transforming 3 -> 6 -> 12. - In-place argument mutation: If f(items) appends 1 to items and returns items, apply_twice(f, box) mutates the caller's original box list to [1, 1]. - External I/O and retries: If f sends an email or charges a card, apply_twice triggers two real-world actions unless the operation is idempotent (safe to repeat without changing the result beyond the first call).

  6. Analyze arrays and linked lists

    Now compare how arrays and linked lists arrange n elements in memory, because every Big-O cost follows directly from that layout:

    Dynamic array (contiguous memory block + spare capacity):
      index:     0     1     2     3     4    (spare)
              +-----+-----+-----+-----+-----+-------+-------+
              |  10 |  20 |  30 |  40 |  50 |   -   |   -   |
              +-----+-----+-----+-----+-----+-------+-------+
      Address of index i = base_address + i * slot_size  --> O(1) random access!
      Inserting at index 0 shifts ALL n elements right   --> O(n)
    
    Doubly linked list (scattered heap nodes connected by prev/next pointers):
      head --> [null|10|*-] <--> [*-|20|*-] <--> [*-|30|null] <-- tail
      Finding index i walks i pointers from head         --> O(n)
      Splicing at a node you ALREADY hold updates links  --> O(1)
    
    • Dynamic array (list in Python, ArrayList in Java):
      • Insert / delete at back (append / pop()): Amortized O(1) — when full, the array allocates a block larger by a constant factor (e.g., 2x) and copies all elements. Over 8 appends with doubling, copies occur at sizes 1, 2, 4, totaling 1 + 2 + 4 = 7 copies (< 1 copy per append on average), though a single resizing append takes O(n) worst-case time.
      • Insert / delete at front or index i: O(n) (O(n - i) element shifts).
      • Search by value: O(n) linear scan if unsorted, or O(log n) via binary search if sorted.
      • Iteration & space: O(n) time (very fast in practice because contiguous memory preloads cleanly into CPU cache lines) and O(n) space (including at most a constant factor of unused capacity).
    • Linked list (singly with head + tail, or doubly linked):
      • Insert / delete at front: O(1) pointer update.
      • Insert / delete at back: Appending at tail is O(1) if a tail pointer is stored (O(n) without tail). Deleting tail is O(1) in a doubly linked list (via tail.prev), but still O(n) in a singly linked list because you must walk from head to find tail's predecessor!
      • Insert / delete in the middle: O(1) only if you already hold a pointer to that node (or its predecessor for singly linked); finding the i-th position first still takes O(n) traversal.
      • Search, iteration & space: O(n) linear search (even if sorted, binary search cannot jump to the middle in O(1)), O(n) iteration (slower per element than arrays due to scattered pointer chasing / cache misses), and O(n) space (1 pointer overhead per node for singly linked, 2 for doubly linked).
  7. Analyze stacks, queues, and how to choose the right structure

    Stacks and queues are abstract access policies built on top of arrays or linked lists:

    • Stack (LIFO — Last-In, First-Out): Supports push, pop, and peek at one end (the top) in O(1) time (amortized O(1) on a dynamic array like Python's list, worst-case O(1) on a linked list). Searching an arbitrary value or iterating all items takes O(n) time, and storage is O(n) space.
    • Queue (FIFO — First-In, First-Out): Supports enqueue at the back and dequeue at the front in O(1) time when backed by a linked list, circular ring buffer, or Python's collections.deque (a doubly linked chain of fixed-size array blocks). Never use list.pop(0) as a queue: shifting all remaining items makes every dequeue O(n) and n dequeues O(n^2). Search and iteration are O(n) time; storage is O(n) space.
    Structure              Insert                      Delete                      Search          Iterate  Space
    ---------------------  --------------------------  --------------------------  --------------  -------  -----
    Dynamic array          Back O(1)*; front/mid O(n)  Back O(1); front/mid O(n)   O(n) / O(logn)  O(n)     O(n)
    Singly linked (+tail)  Front/back/after-node O(1)  Front O(1); back O(n)       O(n)            O(n)     O(n)
    Doubly linked          Front/back/at-node O(1)     Front/back/at-node O(1)     O(n)            O(n)     O(n)
    Stack (LIFO)           Push top: O(1)*             Pop top: O(1)               O(n)            O(n)     O(n)
    Queue (FIFO)           Enqueue back: O(1)*         Dequeue front: O(1)         O(n)            O(n)     O(n)
    (* amortized O(1) when backed by a resizing array or ring buffer; O(log n) search requires a sorted array)
    

    When to choose each: - Dynamic array: Your default choice whenever you read by index, iterate sequentially, sort/binary-search, or mostly append/pop at the end. - Doubly linked list: When you hold direct pointers to middle nodes (for example via a hash map) and must splice or reorder them in O(1), such as an LRU cache. - Stack: Undo/redo history, parsing nested parentheses, expression evaluation, and iterative depth-first search (DFS). - Queue: Breadth-first search (BFS), fair FIFO task scheduling, rate-limiting sliding windows, and producer-consumer buffers.

  8. Complete solution

    from typing import Callable, TypeVar
    
    T = TypeVar("T")
    
    
    def apply_twice(f: Callable[[T], T], x: T) -> T:
        """Return f(f(x)): call f on x, then call f on that result."""
        # Validate upfront so non-callable inputs fail with a clear error message.
        if not callable(f):
            raise TypeError(f"f must be callable, got {type(f).__name__}")
    
        # Phase 1: run f on the initial input x.
        first_result = f(x)
        # Phase 2: feed that output right back into f as its next input.
        second_result = f(first_result)
        return second_result
    
    
    def apply_n(f: Callable[[T], T], x: T, n: int) -> T:
        """Return f applied n times to x; apply_n(f, x, 0) == x."""
        # Check callable(f) even when n == 0 so invalid callables never slip through silently.
        if not callable(f):
            raise TypeError(f"f must be callable, got {type(f).__name__}")
        # Reject booleans explicitly because bool is a subclass of int in Python (True == 1).
        if isinstance(n, bool) or not isinstance(n, int):
            raise TypeError(f"n must be an int, got {type(n).__name__}")
        if n < 0:
            raise ValueError("n must be non-negative")
    
        # current holds the running value after each application (starts at x for n == 0).
        current = x
        # Use an iterative loop instead of recursion so large n (e.g. 100_000) uses O(1) space
        # and never hits Python's ~1000-frame recursion limit.
        for _ in range(n):
            current = f(current)
        return current
    
    
    def make_adder(k: int) -> Callable[[int], int]:
        """Return a pure closure that remembers outer variable k after make_adder returns."""
        def add(v: int) -> int:
            return v + k
        return add
    
    
    def make_call_counter() -> Callable[[int], int]:
        """Return a stateful closure whose call count mutates on every invocation."""
        # calls: integer counter stored in the enclosing scope cell shared across calls.
        calls = 0
    
        def double_and_count(v: int) -> int:
            # nonlocal lets the inner function rebind `calls` in make_call_counter's scope.
            nonlocal calls
            calls += 1
            return v * 2
    
        return double_and_count
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of apply_twice(f, x) like feeding a sheet of dough through the same pasta roller two times in a row: raw dough x enters the roller once to become first_result = f(x), and that exact sheet goes straight back into the roller to produce second_result = f(first_result). Because f is handed in as a pluggable attachment — making apply_twice a higher-order function (a function that accepts or returns another function) — the helper works identically whether f is a plain arithmetic function, a bound string method, or a closure (a function bundled together with variables remembered from the outer scope where it was created). For the data-structure comparison, picture numbered lockers welded in one solid row (an array: you jump to locker #500 in one step by arithmetic, but wedging a new locker at #0 forces all n lockers to slide over) versus a chain of paper clues (a linked list: reaching clue #500 requires walking 500 links from the front, but splicing a new clue right after one you already hold updates just two links).

Naive solutions stumble on subtle runtime costs in both halves of the question. Writing apply_n recursively (f(apply_n(f, x, n - 1))) allocates n call-stack frames and crashes with RecursionError around 1,000 steps, whereas an iterative loop reuses one variable in constant space. On the data-structure side, reaching for Python's list.pop(0) to implement a FIFO queue shifts every remaining item left on each removal, turning n fast O(1) dequeues into an O(n^2) bottleneck.

Walk through our closure trace from Example 2, apply_twice(make_shifter(7), 2): 1. make_shifter(7) returns a callable that retains step = 7 in its captured scope. 2. Inside apply_twice, first_result = f(2) runs 2 + 7 and produces 9. 3. Next, second_result = f(9) runs 9 + 7 and returns 16.

Complexity

  • apply_twice(f, x):
    • Time: O(cost(f)) — we perform one O(1) callable(f) check and invoke f exactly twice in sequence, so runtime is twice the cost of calling f.
    • Space: O(space(f)) (O(1) auxiliary space in apply_twice itself) — we store only two local references (first_result, second_result) beyond whatever memory f uses internally.
  • apply_n(f, x, n):
    • Time: O(n * cost(f)) — the for loop executes n iterations and calls f once per iteration (or zero times in O(1) when n == 0).
    • Space: O(1) auxiliary space beyond f and the current value current, because the loop overwrites current in place instead of building n recursive stack frames.
  • Fundamental data structures (n stored elements):
    • Dynamic array: O(1) random index access via base + i * size; amortized O(1) (meaning O(1) averaged over a sequence of operations despite occasional O(n) resizes) append and O(1) pop at the back; O(n) insert/delete at the front or middle due to shifting elements; O(n) unsorted search (O(log n) binary search if sorted); O(n) cache-friendly iteration; O(n) total space.
    • Linked list: O(n) index lookup and search because pointers must be followed sequentially from an end; O(1) insert/delete at the head, or at any node whose pointer you already hold (O(1) tail delete requires a doubly linked list so tail.prev is known without scanning from head); O(n) iteration; O(n) total space with 1–2 extra pointers per node.
    • Stack (LIFO) & Queue (FIFO): O(1) push/pop at the top of a stack and O(1) enqueue/dequeue at opposite ends of a deque/linked-list queue (amortized O(1) when backed by a resizing array or ring buffer); O(n) linear scan if searched or iterated; O(n) total space.

Edge cases

  • n == 0 in apply_n: Returns x immediately with zero calls to f (verified with a stateful spy function), after still confirming callable(f).
  • Non-callable f (even when n == 0): Raises TypeError right away rather than silently returning x when n == 0 or throwing a cryptic internal error.
  • Boolean or non-integer n: Because bool subclasses int in Python (isinstance(True, int) is True), explicitly rejecting isinstance(n, bool) prevents apply_n(f, x, True) from quietly running once.
  • Negative n: Raises ValueError because an arbitrary black-box function cannot be inverted.
  • Falsy values (None, 0, "", []): Values pass straight through first_result = f(x) without any accidental truthiness checks (if x:) dropping valid inputs.
  • Large n (n = 100,000): Completes smoothly in milliseconds using the iterative loop without overflowing Python's call stack.

Common mistakes

  • Calling f twice on the original x instead of chaining: Expressions like (f(x), f(x)) or 2 * f(x) never feed f(x) into the second call (4 -> 10 -> 28 for 3v - 2 becomes wrong).
  • Calling f at the call site (apply_twice(f(), x)): Adding parentheses invokes f immediately before apply_twice even starts instead of passing the function object f.
  • Creating closures in a loop without binding the loop variable: [lambda v: v + i for i in range(3)] leaves all three lambdas sharing the final value i = 2; capture step=i as a default argument if you want a snapshot per iteration.
  • Claiming linked-list middle insertion is unconditionally O(1): Updating pointers is O(1) only after you hold a reference to that node; walking to index i first still costs O(n).
  • Claiming singly linked list deletion at tail is O(1): Even with a tail pointer, finding the node before tail to become the new tail requires an O(n) scan from head unless the list is doubly linked.
  • Using list.pop(0) for a FIFO queue: Every pop(0) shifts n - 1 references in memory (O(n)); always use collections.deque.popleft() for O(1) dequeues.

Alternative approaches

  • Function composition (compose / twice): Instead of immediately computing a value, write a higher-order function twice(f) that returns a new reusable function v -> f(f(v)). That is cleaner when you plan to apply the composed transformation across millions of elements (for example inside map(twice(clean_text), rows)).
  • functools.reduce: functools.reduce(lambda acc, _: f(acc), range(n), x) expresses apply_n in a single functional expression, though the explicit for loop is much easier for readers to trace and debug.

Follow-up questions

  • Under what conditions can repeated function application run in fewer than linear steps? Not when f is an arbitrary black box whose behavior can only be observed one step at a time. However, if f has known mathematical structure (such as a linear function f(v) = a * v + b, a matrix multiplication, or a finite-domain permutation table of size M), you can compose f with itself by binary exponentiation (repeated squaring: f^2, f^4, f^8, ...) to compute apply_n in O(log n) compositions — turning 1,000,000 steps into ~20 steps!
  • If several threads call the higher-order helper at the same time, what determines whether execution is thread-safe? apply_twice itself holds only local stack variables (first_result, second_result), so its thread safety depends entirely on f. If f is a pure function (like make_adder(7)), concurrent calls are completely thread-safe; if f mutates shared state (like make_call_counter updating nonlocal calls or mutating a shared dictionary), calls += 1 is not atomic across threads and requires a threading.Lock inside f.
  • Why does a constant-time Least Recently Used (LRU) cache combine a hash map with a doubly linked list instead of relying on either structure alone? Neither data structure can solve LRU caching in O(1) alone: a hash map gives O(1) average key lookup but tracks no recency order, while an array takes O(n) shifts to move a recently accessed item to the front. Pairing a hash map (key -> Node) with a doubly linked list ordered from most-recent (head) to least-recent (tail) lets you jump straight to any key's node in O(1), splice that node out via its prev/next pointers and reattach it at head in O(1), and evict tail in O(1) when full.

Follow-up questions

Similar questions

More eBay interview questions

All 41 eBay questions →