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:
-
apply_twice(f: Callable[[T], T], x: T) -> T- Evaluates
f(x)first, then passes that return value intofa second time and returnsf(f(x)). fmay be any Python callable: adeffunction, alambda, a lexical closure, a built-in function, a bound or unbound method, afunctools.partialwrapper, or an instance of a class defining__call__.- Raises
TypeErroriffis not callable.
- Evaluates
-
apply_n(f: Callable[[T], T], x: T, n: int) -> T- Applies
fsequentiallyntimes starting fromx. Whenn == 0, returnsxdirectly without invokingf. Whenn >= 1, invokesfon the running valuentimes in order so any stateful callable observesndistinct calls. - Raises
TypeErroriffis not callable (even whenn == 0). - Raises
TypeErrorifnis not anintor ifnis abool(TrueorFalse). - Raises
ValueErrorifn < 0. - Must execute iteratively in
O(1)auxiliary stack space so large iteration counts (such asn = 100_000) do not trigger aRecursionError.
- Applies
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
fmust accept its own return type (Callable[[T], T]); non-callablefvalues must raiseTypeError.0 <= n <= 100_000for validapply_ncalls (n < 0raisesValueError; non-integer or booleannraisesTypeError).- Valid falsy data values (
0,None,"",[]) must pass throughfunmodified by truthiness checks. - Auxiliary call-stack space in
apply_twiceandapply_nmust beO(1)beyond the memory used byfitself.
Step-by-step walkthrough
Understand the goal and the type contract
This problem combines two core software-engineering fundamentals:
- Higher-order functions and state: Implement
apply_twice(f, x)to computef(f(x)), generalize it iteratively toapply_n(f, x, n)fornsequential applications, and explain how callable values, closures, and side effects interact. - 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 ]---> 28Notice the immediate type rule: because
fmust consume its own return value on the second step,f's output type must be valid asf's input type (Callable[[T], T]). Passinglenwith"abc"works once (len("abc") -> 3), then crashes on the second step (len(3)raisesTypeError).- Higher-order functions and state: Implement
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_twicethat 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_resultAny Python callable works automatically: a
deffunction, alambda, a built-in likeabs, a bound method like"-".join, afunctools.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)Generalizing to n applications iteratively
Interviewers frequently ask right away: "What if we want to apply
fntimes?" Applyingfzero times (n = 0) leavesxunchanged (the mathematical identityf^0(x) = x), whilen < 0has no general meaning because an arbitrary black-box functionfhas 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 withRecursionErroraroundn = 1,000in standard Python. A simpleforloop updates one variable inO(1)extra memory even whenn = 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 currentClosures: 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 addWhen
add7 = make_adder(7)runs,add7holds a hidden cell pointing tok = 7, soapply_twice(add7, 2)computes2 -> 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
lambdawas created. Creating functions inside aforloop makes every function share the exact same loop variablei:# 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.)
Side effects and mutable state
A pure function computes its return value solely from its arguments and modifies nothing outside itself (
add7above 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_twiceinvokesftwo 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_countHighlight three practical side-effect consequences in an interview: - Stateful closures (
nonlocal): Callingapply_twice(make_call_counter(), 3)incrementscallsfrom0 -> 1 -> 2while transforming3 -> 6 -> 12. - In-place argument mutation: Iff(items)appends1toitemsand returnsitems,apply_twice(f, box)mutates the caller's originalboxlist to[1, 1]. - External I/O and retries: Iffsends an email or charges a card,apply_twicetriggers two real-world actions unless the operation is idempotent (safe to repeat without changing the result beyond the first call).Analyze arrays and linked lists
Now compare how arrays and linked lists arrange
nelements 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 (
listin Python,ArrayListin Java):- Insert / delete at back (
append/pop()): AmortizedO(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 sizes1, 2, 4, totaling1 + 2 + 4 = 7copies (< 1copy per append on average), though a single resizing append takesO(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, orO(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) andO(n)space (including at most a constant factor of unused capacity).
- Insert / delete at back (
- Linked list (singly with
head+tail, or doubly linked):- Insert / delete at front:
O(1)pointer update. - Insert / delete at back: Appending at
tailisO(1)if atailpointer is stored (O(n)withouttail). DeletingtailisO(1)in a doubly linked list (viatail.prev), but stillO(n)in a singly linked list because you must walk fromheadto findtail'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 thei-th position first still takesO(n)traversal. - Search, iteration & space:
O(n)linear search (even if sorted, binary search cannot jump to the middle inO(1)),O(n)iteration (slower per element than arrays due to scattered pointer chasing / cache misses), andO(n)space (1pointer overhead per node for singly linked,2for doubly linked).
- Insert / delete at front:
- Dynamic array (
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, andpeekat one end (the top) inO(1)time (amortizedO(1)on a dynamic array like Python'slist, worst-caseO(1)on a linked list). Searching an arbitrary value or iterating all items takesO(n)time, and storage isO(n)space. - Queue (FIFO — First-In, First-Out): Supports
enqueueat the back anddequeueat the front inO(1)time when backed by a linked list, circular ring buffer, or Python'scollections.deque(a doubly linked chain of fixed-size array blocks). Never uselist.pop(0)as a queue: shifting all remaining items makes every dequeueO(n)andndequeuesO(n^2). Search and iteration areO(n)time; storage isO(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.- Stack (LIFO — Last-In, First-Out): Supports
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 oneO(1)callable(f)check and invokefexactly twice in sequence, so runtime is twice the cost of callingf. - Space:
O(space(f))(O(1)auxiliary space inapply_twiceitself) — we store only two local references (first_result,second_result) beyond whatever memoryfuses internally.
- Time:
apply_n(f, x, n):- Time:
O(n * cost(f))— theforloop executesniterations and callsfonce per iteration (or zero times inO(1)whenn == 0). - Space:
O(1)auxiliary space beyondfand the current valuecurrent, because the loop overwritescurrentin place instead of buildingnrecursive stack frames.
- Time:
- Fundamental data structures (
nstored elements):- Dynamic array:
O(1)random index access viabase + i * size; amortizedO(1)(meaningO(1)averaged over a sequence of operations despite occasionalO(n)resizes) append andO(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 sotail.previs known without scanning fromhead);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 andO(1)enqueue/dequeue at opposite ends of adeque/linked-list queue (amortizedO(1)when backed by a resizing array or ring buffer);O(n)linear scan if searched or iterated;O(n)total space.
- Dynamic array:
Edge cases
n == 0inapply_n: Returnsximmediately with zero calls tof(verified with a stateful spy function), after still confirmingcallable(f).- Non-callable
f(even whenn == 0): RaisesTypeErrorright away rather than silently returningxwhenn == 0or throwing a cryptic internal error. - Boolean or non-integer
n: Becauseboolsubclassesintin Python (isinstance(True, int)isTrue), explicitly rejectingisinstance(n, bool)preventsapply_n(f, x, True)from quietly running once. - Negative
n: RaisesValueErrorbecause an arbitrary black-box function cannot be inverted. - Falsy values (
None,0,"",[]): Values pass straight throughfirst_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
ftwice on the originalxinstead of chaining: Expressions like(f(x), f(x))or2 * f(x)never feedf(x)into the second call (4 -> 10 -> 28for3v - 2becomes wrong). - Calling
fat the call site (apply_twice(f(), x)): Adding parentheses invokesfimmediately beforeapply_twiceeven starts instead of passing the function objectf. - 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 valuei = 2; capturestep=ias a default argument if you want a snapshot per iteration. - Claiming linked-list middle insertion is unconditionally
O(1): Updating pointers isO(1)only after you hold a reference to that node; walking to indexifirst still costsO(n). - Claiming singly linked list deletion at
tailisO(1): Even with atailpointer, finding the node beforetailto become the new tail requires anO(n)scan fromheadunless the list is doubly linked. - Using
list.pop(0)for a FIFO queue: Everypop(0)shiftsn - 1references in memory (O(n)); always usecollections.deque.popleft()forO(1)dequeues.
Alternative approaches
- Function composition (
compose/twice): Instead of immediately computing a value, write a higher-order functiontwice(f)that returns a new reusable functionv -> f(f(v)). That is cleaner when you plan to apply the composed transformation across millions of elements (for example insidemap(twice(clean_text), rows)). functools.reduce:functools.reduce(lambda acc, _: f(acc), range(n), x)expressesapply_nin a single functional expression, though the explicitforloop 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
fis an arbitrary black box whose behavior can only be observed one step at a time. However, iffhas known mathematical structure (such as a linear functionf(v) = a * v + b, a matrix multiplication, or a finite-domain permutation table of sizeM), you can composefwith itself by binary exponentiation (repeated squaring:f^2,f^4,f^8, ...) to computeapply_ninO(log n)compositions — turning1,000,000steps into ~20steps! - If several threads call the higher-order helper at the same time, what determines whether execution is thread-safe?
apply_twiceitself holds only local stack variables (first_result,second_result), so its thread safety depends entirely onf. Iffis a pure function (likemake_adder(7)), concurrent calls are completely thread-safe; iffmutates shared state (likemake_call_counterupdatingnonlocal callsor mutating a shared dictionary),calls += 1is not atomic across threads and requires athreading.Lockinsidef. - 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 givesO(1)average key lookup but tracks no recency order, while an array takesO(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 inO(1), splice that node out via itsprev/nextpointers and reattach it atheadinO(1), and evicttailinO(1)when full.
Follow-up questions
- Under what conditions can repeated function application run in fewer than linear steps?
- If several threads call the higher-order helper at the same time, what determines whether execution is thread-safe?
- 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?
Similar questions
- Randomized Ad Slot Allocation Under Per-User Caps
- Days Until a Higher Temperature
- Count Orthogonal Land Regions
- Shortest Path for a Leg-Blocked Xiangqi Horse
- Validate Numeric String Grammar
- Top K Frequent Integers
More eBay interview questions
- Days Until a Higher Temperature Medium
- Largest Tank Area Between Vertical Walls Medium
- Randomized Ad Slot Allocation Under Per-User Caps Medium Pro
- Cross-Team Ownership, Manager Disagreements, and Slipping Skip-Level Deadlines Easy Pro
- Global Org Fit, Role Alignment, and On-Call Ownership Easy Pro
- Marketplace Payment Dispute Resolution Service Medium Pro
- Workplace Lunch Ordering with Daily Vendor Rotation Medium Pro
- Marketplace Product Search and Typeahead System Medium Pro
- Real-Time Top-10 Marketplace Bestseller Leaderboard Medium Pro
- Frequency-Capped Ad Placement API Medium Pro