Algorithmic Problem-Solving and Data Structure Selection Questions
The higher-order meta-skill of attacking an unfamiliar problem: recognizing problem archetypes and mapping them to known techniques, decomposing under constraints, and choosing, composing, or designing the right data structures to meet specified operation costs (LRU cache, min-stack, ordered maps, disjoint-set/union-find). Covers reasoning about trade-offs between competing structures and approaches, working through medium-to-hard problems methodically, handling problem variations, and communicating an approach before coding. The connective-tissue topic that ties the individual structure and algorithm topics together, rather than any single structure or algorithm.
Compare a contiguous array and a singly linked list on random access, insertion/deletion at head/middle/tail, memory overhead, and cache locality. For a workload that is mostly random reads versus one that is mostly insertions and deletions in the middle, which would you pick and why?
Sample Answer
Direct answer
An array gives O(1) index-based random access and is cache-friendly, because its elements sit in one contiguous block of memory that the CPU can pull into cache together. A singly linked list gives O(1) insertion or deletion once you already hold a reference to the splice point, at the cost of O(n) traversal to reach any given position and extra per-node memory overhead. For a workload that is mostly random reads, pick an array (or dynamic array); for a workload that is mostly insertions and deletions in the middle where you already hold the relevant node reference, a linked list wins.
Structured elaboration
| Dimension | Array | Singly linked list |
|---|---|---|
| Random access by index | O(1) | O(n), must walk from the head |
| Insert/delete at head | O(n), shifts every remaining element | O(1), relink the head reference |
| Insert/delete at tail | O(1) amortized (averaged over a sequence of operations; dynamic array resize) | O(1) only if a tail reference is separately maintained, otherwise O(n) to reach it |
| Insert/delete in the middle | O(n), shifts elements | O(1) to relink, but only if you already hold a reference to the node just before the splice point; otherwise O(n) just to reach it |
| Memory overhead | None beyond the elements themselves, plus occasional unused resize slack | Each node carries at least one extra reference beyond its value, a larger overhead per element |
| Cache locality | Contiguous memory means sequential and even random access both benefit from data already sitting in cache | Each node is typically a separate heap allocation, so following references jumps around memory ("pointer chasing"), producing far more cache misses per traversal |
The contiguous-versus-non-contiguous memory allocation framing is exactly this same dimension stated differently: contiguous storage is what gives arrays both their cache locality and their index arithmetic; non-contiguous, per-node allocation is what gives linked lists their cheap local splicing at the cost of locality. In a garbage-collected (GC) language, this also affects collector pressure: many small linked-list node objects mean more individual objects for the garbage collector to track and scan, compared to one contiguous array allocation holding the same data.
Worked example
Consider inserting a new element in the middle of a ten-item collection, repeatedly, as items are typed into an editable list. With an array, each insertion must shift every element after the insertion point one slot over, an O(n) cost per insertion regardless of whether you know exactly where to insert. With a singly linked list, if the editing position is tracked by an existing reference to the node just before it (as a cursor would be in a text-editing context), each insertion is a pure O(1) relink; but if you only know the position as an index and must first walk from the head to reach it, the linked list gains nothing over the array for that access, since both now cost O(n) overall. This is why the deciding factor is not "array versus linked list" in the abstract, but whether the workload naturally hands you a reference to the splice point or only an index.
Trade-offs & pitfalls
Assuming "O(1) insertion" for a linked list means fast in absolute terms is a common mistake: reaching the splice point is usually the dominant cost unless a reference to it is already in hand from a prior traversal or an auxiliary index. Ignoring the per-element memory overhead ratio is another: a linked list of single integers can use several times the memory of the equivalent array, because the pointer overhead per node is fixed regardless of how small the stored value is. Modern hybrid structures such as a deque (double-ended queue) or a rope address parts of this trade-off by chunking data into contiguous blocks rather than choosing purely one extreme or the other.
Compare quicksort, merge sort, and heap sort on average-case and worst-case time, extra space, and stability. Given a dataset that is nearly sorted already, or one where worst-case guarantees matter more than average speed, which would you pick and why?
Sample Answer
Direct answer
Quicksort is in-place with average time O(nlogn) but a worst case of O(n2) on an unlucky pivot sequence; merge sort and heap sort both guarantee O(nlogn) in every case. Merge sort needs O(n) extra space and is stable; heap sort needs only O(1) extra space but is not stable; quicksort's extra space is O(logn) for the recursion stack on average, but can grow to O(n) in the worst case. For nearly-sorted data, pick an adaptive sort such as TimSort (the hybrid merge/insertion sort behind Python's and Java's built-in sort); when a guaranteed worst case matters more than average speed, pick heap sort or merge sort, never plain quicksort.
Structured elaboration
| Algorithm | Average time | Worst time | Extra space | Stable | Adaptive to existing order |
|---|---|---|---|---|---|
| Quicksort | O(nlogn) | O(n2) | O(logn) avg, O(n) worst (stack) | No (not without extra bookkeeping) | No |
| Merge sort | O(nlogn) | O(nlogn) | O(n) | Yes | Only the natural-merge variant |
| Heap sort | O(nlogn) | O(nlogn) | O(1) | No | No |
| TimSort (hybrid) | O(nlogn) | O(nlogn) | O(n) | Yes | Yes, detects existing runs |
Nearly-sorted input
Plain quicksort and plain top-down merge sort are not adaptive: both do the same O(nlogn) work regardless of how ordered the input already is. TimSort is: it scans for existing ascending or descending runs, extends and merges them, and degrades toward close to linear work as the input approaches already-sorted. For nearly-sorted data, reach for TimSort (or, if you must hand-roll something, a natural merge sort) rather than a textbook quicksort or merge sort.
Worst-case guarantees matter more than average speed
Both heap sort and merge sort guarantee O(nlogn) in every case; quicksort does not, no matter how the pivot is chosen, because an adversary (or, unintentionally, already-sorted or already-reverse-sorted input under a naive pivot rule) can always construct a sequence that degrades a fixed pivot strategy to O(n2). Choose heap sort when the extra O(n) memory merge sort needs is unavailable and stability is not required; choose merge sort when stability is required alongside the worst-case guarantee and the memory budget allows it.
Two side notes worth naming explicitly
- Parallelization on resource-constrained devices: merge sort's divide phase maps cleanly onto independent worker threads or cores (each half sorts independently before a merge step), which is attractive on a multi-core mobile device; the cost is the extra O(n) buffer merge sort needs, which is a real constraint on memory-limited hardware. Quicksort's partitions can also be sorted concurrently, but partition sizes are unpredictable (a skewed pivot gives one thread almost all the work), so load balancing is harder to reason about.
- Cross-language floating-point sort determinism: when the same data is sorted by comparator across different languages or platforms, an unstable sort's tie-breaking for equal keys is unspecified and can differ, and NaN comparisons under IEEE 754 floating point are neither less-than nor greater-than any value, which breaks the total-order assumption most sort implementations rely on. If reproducible ordering across systems matters (for example, deterministic test fixtures or replaying a pipeline), use a stable sort and either exclude or explicitly place NaNs, rather than relying on the default comparator.
Worked example
A concrete way to see the worst case: implement a plain quicksort that always pivots on the last element, and run it on an already-sorted array.
def quicksort_last_pivot_count(a: list[int]) -> int:
"""
Naive quicksort that always pivots on the last element.
Returns the number of comparisons performed (element-to-pivot checks).
"""
comparisons = 0
def sort(lo: int, hi: int) -> None:
nonlocal comparisons
if lo >= hi:
return
pivot = a[hi]
store = lo
for i in range(lo, hi):
comparisons += 1
if a[i] < pivot:
a[i], a[store] = a[store], a[i]
store += 1
a[store], a[hi] = a[hi], a[store]
sort(lo, store - 1)
sort(store + 1, hi)
sort(0, len(a) - 1)
return comparisons
if __name__ == "__main__":
for n in [6, 10, 20]:
already_sorted = list(range(n))
c = quicksort_last_pivot_count(already_sorted)
expected = n * (n - 1) // 2
print(f"n={n}: comparisons={c}, n(n-1)/2={expected}")
Running this prints:
n=6: comparisons=15, n(n-1)/2=15
n=10: comparisons=45, n(n-1)/2=45
n=20: comparisons=190, n(n-1)/2=190
Every partition step on already-sorted input with a last-element pivot puts everything on one side, so the recursion depth is n and the total comparisons are exactly n(n−1)/2=Θ(n2), confirmed by the counts matching the closed-form prediction at every size tested. A randomized or median-of-three pivot choice avoids this specific failure mode but does not eliminate the worst case in general, only make it exponentially unlikely to hit by chance.
Trade-offs & pitfalls
The most common wrong turn is treating quicksort as unconditionally the fastest choice: on already-sorted or reverse-sorted input under a naive pivot rule, it is the slowest of the three by an order of magnitude, as the worked example shows directly. A second common gap is forgetting that merge sort's memory cost is real: at large enough n, the O(n) auxiliary buffer competes with other memory pressure, which is exactly why external (disk-based) sorting is built on multi-way merge rather than quicksort, since merge sort's sequential access pattern suits disk or network I/O far better than quicksort's more random access pattern. A third trap is ignoring stability when it silently matters: if you sort by a secondary key after already sorting by a primary key, only a stable sort preserves the primary ordering among equal secondary keys; using an unstable sort there produces a result that looks correct on small examples but is wrong in general.
What is the difference between 'in-place' and 'O(1) extra space'? Explain how recursion affects that accounting even when a function never allocates an explicit second array or list.
Sample Answer
Direct answer
"In-place" and "O(1) extra space" are usually used interchangeably to mean an algorithm transforms its input using only a constant amount of auxiliary memory beyond the input and output themselves. Recursion complicates that accounting: every recursive call adds a stack frame (its arguments, local variables, and a return address), so a recursive function that touches no second array or list can still use O(n) extra memory through the call stack alone, memory that is easy to forget because it never shows up as an explicit variable in the code.
Structured elaboration
What counts as "extra" space
The convention is to count space beyond the input and the required output. A function that reverses an array by swapping elements in the same array is O(1) extra space by this convention, even though the array itself is O(n), because that space was already accounted for as the input. Auxiliary structures the algorithm allocates on top of that, a second array, a hash map, or the call stack, are what get charged against the space bound.
How recursion hides space in the call stack
Each recursive call is not free: the runtime pushes a new stack frame holding that call's parameters and local variables, and does not pop it until the call returns. A recursive function with depth d therefore uses O(d) stack space regardless of what its explicit variables look like. For a tree of height h, naive recursion is O(h) stack space, which is O(logn) for a balanced tree but O(n) for a completely skewed one; for a straightforward recursive Fibonacci, the recursion depth (and thus stack space) is O(n) even though each individual call only holds a couple of integers.
Three ways to convert hidden stack space into genuine O(1) space
- Threading (Morris traversal): temporarily rewrite null-looking child pointers to point back up the tree, walk using those threads instead of recursing, then restore the original structure. No stack, no recursion, just pointer rewrites.
- Iterative looping with an accumulator: replace a linear recursion (like naive Fibonacci) with a loop carrying only the last one or two values needed, discarding everything else.
- Recurse on the smaller side, loop on the larger (tail-call style elimination): for divide-and-conquer algorithms like quicksort, always making the recursive call on the smaller partition bounds the recursion depth by O(logn) even in the worst case, because the smaller side can be at most half the remaining size at each level.
Worked example
# 1) Morris inorder traversal: O(1) extra space, no recursion, no explicit stack
def morris_inorder(root):
out = []
cur = root
while cur:
if not cur.left:
out.append(cur.val)
cur = cur.right
else:
pred = cur.left
while pred.right and pred.right is not cur:
pred = pred.right
if not pred.right:
pred.right = cur # thread to come back later
cur = cur.left
else:
pred.right = None # remove the thread, tree restored
out.append(cur.val)
cur = cur.right
return out
# 2) Iterative Fibonacci: O(1) extra space, versus O(n) recursion-stack depth for the naive recursive version
def fib(n):
if n < 2:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
# 3) Quicksort: recurse on the smaller partition, loop on the larger, bounding stack depth to O(log n)
def partition(arr, lo, hi):
pivot = arr[hi]
i = lo
for j in range(lo, hi):
if arr[j] < pivot:
arr[i], arr[j] = arr[j], arr[i]
i += 1
arr[i], arr[hi] = arr[hi], arr[i]
return i
def quicksort(arr, lo=0, hi=None):
if hi is None:
hi = len(arr) - 1
while lo < hi:
p = partition(arr, lo, hi)
if p - lo < hi - p:
quicksort(arr, lo, p - 1)
lo = p + 1
else:
quicksort(arr, p + 1, hi)
hi = p - 1
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
n = {v: Node(v) for v in range(1, 8)}
n[4].left, n[4].right = n[2], n[6]
n[2].left, n[2].right = n[1], n[3]
n[6].left, n[6].right = n[5], n[7]
print(morris_inorder(n[4]))
print([fib(i) for i in range(10)])
import random
random.seed(5)
original = [random.randint(0, 100) for _ in range(50)]
arr = original[:]
quicksort(arr)
print("quicksort matches sorted():", arr == sorted(original))
Running this prints the Morris traversal [1, 2, 3, 4, 5, 6, 7] (the tree's inorder sequence, confirming the temporary threads were fully removed and the structure is intact), the Fibonacci sequence [0, 1, 1, 2, 3, 5, 8, 13, 21, 34], and quicksort matches sorted(): True, confirming the in-place quicksort produces the same order as Python's own sorted() on the same seeded input.
Key points
- Morris traversal never recurses and never allocates an explicit stack, it reuses the tree's own null pointers as temporary bookkeeping, then undoes that bookkeeping before moving on.
- The iterative Fibonacci keeps exactly two rolling values (
a,b) instead of a call stack that grows withn. - "Recurse smaller, loop larger" is not just a performance tweak, it is what guarantees the quicksort recursion depth is O(logn) even on adversarial input, since the recursive branch always operates on a piece at most half the current size.
Complexity notes
Morris traversal: O(n) time (each edge is traversed a bounded number of times to set up and tear down threads), O(1) extra space. Naive recursive Fibonacci: O(2n) time and O(n) stack space (depth n); the iterative version is O(n) time and O(1) space. Naive quicksort recursion: O(n) worst-case stack depth (already-sorted input recursing on the full remaining range each time); recursing on the smaller side bounds it to O(logn) worst case.
Trade-offs & pitfalls
A recursive solution that "looks" O(1) space because it declares no arrays is a common trap, always ask separately what the maximum recursion depth is and whether the language or runtime performs tail-call optimization (most mainstream production runtimes, including CPython, do not, so a "tail recursive" Python function still accumulates real stack frames). Morris traversal trades a temporary, carefully-undone mutation of the tree's own pointers for the stack savings, which is a real complexity cost in the code even though the asymptotic space bound improves, and it is unsafe on a tree that might be read concurrently while being traversed, since the tree is briefly in a modified state.
Explain the difference between breadth-first and depth-first traversal of a graph: what order nodes are visited in, what each one is typically implemented with, and their time and space complexity. When would you reach for one over the other?
Sample Answer
Direct answer
Breadth-first search (BFS) visits a graph level by level using a first-in-first-out queue: it fully explores every node at the current distance from the source before moving one edge farther out, which is exactly why the first time BFS reaches a node, it has found a shortest path to it in edge count (for unweighted graphs). Depth-first search (DFS) instead follows one path as far as it can, using a stack (explicit or via recursion), only backtracking once it hits a dead end. Both run in O(V+E) time and O(V) space on an adjacency-list graph with V vertices and E edges; reach for BFS when you need shortest paths or level-order information, and for DFS when you need to explore structure like cycles, connectivity, or an ordering that depends on finishing an entire subtree first, as in topological sort.
Structured elaboration
Mechanics
- BFS: enqueue the source, mark it visited, then repeatedly dequeue a node, and for each unvisited neighbor, mark it visited and enqueue it. The queue's contents at any point are exactly the current "frontier" one edge past the last fully-processed layer.
- DFS: push the source (or call recursively), mark it visited, and for each unvisited neighbor, recurse (or push) immediately, only returning to try the next neighbor after that whole branch is exhausted.
- Marking a node visited at the moment it's enqueued (BFS) or entered (DFS), not when it's dequeued or finished, avoids adding the same node to the queue or stack more than once.
Recursive versus iterative DFS
Recursive DFS is simpler to write, since the call stack does the bookkeeping for you, but it risks a stack overflow on a very deep graph (recursion depth is bounded by the language's call-stack limit, for example Python's default recursion limit of 1000). Iterative DFS with an explicit stack avoids that limit, at the cost of manually tracking which neighbors of a node remain to be visited.
Deep-and-narrow versus wide-and-shallow graphs
Both algorithms are O(V) space in the worst case, but the shape of the graph determines which one actually uses less memory in practice: on a long, narrow chain, DFS's memory stays proportional to the current depth, which can be far less than BFS's frontier at the widest level; on a short, very wide graph (many nodes one edge from the source), BFS's frontier can be large while DFS's stack stays shallow. Neither algorithm is unconditionally more memory-efficient; it depends on the graph's shape.
Cycle detection and topological sort
A DFS-based topological sort (or cycle check) needs three states per node, not a single visited flag: unvisited, in-progress (currently on the recursion stack), and finished. An edge to an in-progress node is a back edge and signals a cycle; an edge to an already-finished node is fine and doesn't indicate one. A binary visited flag can't tell these two cases apart.
Worked example
from collections import deque
adj = {0: [1, 2], 1: [3], 2: [3], 3: []}
def bfs(start):
visited = {start}
order = []
queue = deque([start])
while queue:
u = queue.popleft()
order.append(u)
for v in adj[u]:
if v not in visited:
visited.add(v)
queue.append(v)
return order
def dfs(start):
visited = set()
order = []
def visit(u):
visited.add(u)
order.append(u)
for v in adj[u]:
if v not in visited:
visit(v)
visit(start)
return order
if __name__ == "__main__":
print("BFS:", bfs(0))
print("DFS:", dfs(0))
Running this prints BFS: [0, 1, 2, 3] and DFS: [0, 1, 3, 2]. BFS visits both of node 0's neighbors (1 and 2) before going any deeper, reaching 3 only after the whole first layer is done. DFS instead commits to the first neighbor, 1, follows it all the way to 3, then backtracks and only picks up 2 afterward.
Trade-offs & pitfalls
- DFS does not generally find shortest paths in edge count; only BFS gives that guarantee on unweighted graphs.
- Forgetting to mark a node visited until it's dequeued (rather than when it's enqueued) in BFS lets the same node be enqueued multiple times through different neighbors, wasting work even though the final result stays correct once a visited check also guards processing.
- For weighted graphs where edge costs differ, neither plain BFS nor DFS finds the shortest path by cost; that needs Dijkstra's algorithm or A* search instead.
- A disconnected graph needs a traversal restarted from every unvisited node to cover every component; a single BFS or DFS call from one source only reaches that source's connected component.
Complexity
Time: O(V+E) for both, since every vertex and every edge is examined once. Space: O(V) for both (BFS's queue plus visited set; DFS's recursion stack or explicit stack plus visited set).
Edge cases
- Disconnected graphs: restart the traversal from each unvisited node to reach every component.
- Self-loops and multi-edges: a visited check naturally prevents a self-loop from causing infinite reprocessing.
- A single-node graph with no edges: both traversals just return that one node.
Implement binary search on a sorted array: return the index of a target value, or a sentinel if it is not present. Walk through the loop invariant you maintain so you can convince yourself it terminates correctly and never reads out of bounds.
Sample Answer
Direct answer
Maintain an inclusive range [lo, hi] that is the only place the target could still be. At each step, compare the target to the middle element and shrink the range to whichever half could still contain it. The loop ends when lo > hi, at which point the target is not present, so return a sentinel (commonly -1). This runs in O(logn) time and O(1) space.
Structured elaboration
The loop invariant. Before every iteration, "if the target is present in the array, its index lies within [lo, hi]" holds. Each iteration either returns immediately (found it) or moves lo past mid, or hi before mid, which strictly shrinks the range while preserving the invariant.
Why it terminates. Every iteration where the target is not found at mid removes at least the midpoint from consideration, so hi - lo at least halves (roughly) each time; the range cannot shrink forever without becoming empty, so the loop reaches lo > hi within O(logn) steps.
Why it never reads out of bounds. mid is always computed strictly between the current lo and hi, both of which start as, and remain, valid indices into the array (or the empty range lo > hi, which the loop condition catches before computing mid at all).
The overflow bug (reviewing someone else's code). Suppose a colleague wrote mid = (lo + hi) // 2. In Python this is safe because integers have arbitrary precision, but in a fixed-width-integer language such as Java or C++, lo + hi can exceed the maximum representable value for a very large array and silently wrap around, producing a corrupted mid that can throw the search out of bounds or into an infinite loop. Writing mid = lo + (hi - lo) // 2 avoids this because hi - lo never exceeds the array's size, so the sum can never overflow the way lo + hi can.
Worked example
def binary_search(nums: list[int], target: int) -> int:
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2 # avoids the lo + hi overflow above
if nums[mid] == target:
return mid
elif nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
if __name__ == "__main__":
nums = [1, 3, 5, 7, 9, 11]
print(binary_search(nums, 7), binary_search(nums, 4))
Running this prints 3 -1. For target 7: lo=0, hi=5, mid=2 (value 5, too small, lo becomes 3); lo=3, hi=5, mid=4 (value 9, too big, hi becomes 3); lo=3, hi=3, mid=3 (value 7, match, return 3). For target 4: the range keeps shrinking until lo exceeds hi without ever matching, returning -1.
Complexity
Time: O(logn), since each iteration discards at least half of the remaining [lo, hi] range.
Space: O(1) for this iterative version, since only a fixed number of index variables (lo, hi, mid) are held regardless of the array's size.
Edge cases
- Empty array (
len(nums) == 0):lo = 0andhi = -1start withlo > hi, so the loop body never runs and the sentinel-1is returned immediately. - Target smaller than every element or larger than every element: the range shrinks to empty without ever matching, again returning the sentinel.
- Array with duplicate values: this exact routine returns the index of some matching element, not necessarily the first or last one; that is a distinct, slightly more involved variant.
Trade-offs & pitfalls
A recursive version expresses the same logic but spends O(logn) call-stack space doing so, where this iterative version uses O(1). The other classic source of infinite loops or off-by-one errors is mixing bound conventions, for example initializing hi = len(nums) (a half-open convention) while writing the rest of the loop as if hi were an inclusive index; pick one convention and keep it consistent throughout.
Unlock Full Question Bank
Get access to all 27 Algorithmic Problem-Solving and Data Structure Selection interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.