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.
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.
A dynamic array (Python list, Java ArrayList, C++ vector) doubles its backing capacity whenever it fills up. Explain why append is still considered O(1) on average even though an individual append can trigger an O(n) copy, and what would happen to that guarantee if the growth strategy added a fixed amount of capacity each time instead of doubling it.
Sample Answer
Direct answer
Append is O(1) amortized (amortized meaning the average cost per operation across a whole sequence of operations, not the cost of any single call) because the expensive O(n) resize-and-copy step happens rarely, and its cost can be spread over the many cheap O(1) appends that occur between resizes. Summed over any sequence of n appends, the total work stays proportional to n, so the average cost per append is a constant. That guarantee depends specifically on doubling (or any fixed multiplicative growth factor); if capacity instead grew by a fixed additive amount each time, resizes become frequent enough that total copying work grows like O(n2), which makes the amortized cost per append O(n) instead of O(1).
Structured elaboration
Proof sketch for doubling (α=2)
Start empty and perform n appends. Each append either writes into a free slot (cost 1) or triggers a resize that copies the current m elements before writing. Because capacity doubles, the sizes copied across all resizes form the series 1,2,4,8,… up to just under n:
1+2+4+⋯+2k<2n
So total cost across all n appends is at most n (the simple writes) plus 2n (the copying), giving:
amortized cost≤nn+2n=3=O(1)
For a general multiplicative factor α>1, the copied sizes form a geometric series bounded by α−1α⋅n, so the amortized constant is roughly 1+α−1α: about 3 for α=2, about 4 for α=1.5, and growing without bound as α→1+.
What breaks with fixed additive growth
If capacity instead grows by a fixed amount c each time (not multiplied), resizes happen roughly every c appends, and the k-th resize copies about kc existing elements. Summed over n/c resizes:
total copy cost=k=1∑n/ckc=c⋅2(n/c)(n/c+1)≈2cn2
Total work across n appends is now O(n2), so the amortized cost per append is O(n2)/n=O(n): linear per operation on average, not constant. Additive growth trades away the amortized guarantee entirely; it doesn't just make the constant worse, it changes the complexity class.
Reference point (not a claim about your specific runtime, just why factors below 2 are common): production dynamic-array implementations often deliberately avoid a factor-2 growth to reduce peak wasted memory, accepting a larger amortized constant in exchange (for example, growth factors noticeably below 2 are common in real-world implementations). The trade-off is always time (fewer resizes) versus space (less transient waste).
Worked example
Running the doubling and fixed-increment growth strategies and tracking total bytes copied per element appended (all inputs pinned, no timing claims, just operation counts):
def total_copy_cost_doubling(n: int) -> tuple[int, int]:
"""Simulates n appends into a dynamic array that doubles capacity
on overflow. Returns (total elements copied across all resizes,
number of resizes)."""
cap = 1
size = 0
total_copy = 0
resizes = 0
for _ in range(n):
if size == cap:
total_copy += cap # copy every existing element
cap *= 2
resizes += 1
size += 1
return total_copy, resizes
def total_copy_cost_additive(n: int, c: int) -> tuple[int, int]:
"""Same simulation, but capacity grows by a fixed amount c each
time instead of doubling."""
cap = 0
size = 0
total_copy = 0
resizes = 0
for _ in range(n):
if size == cap:
total_copy += cap
cap += c
resizes += 1
size += 1
return total_copy, resizes
if __name__ == "__main__":
print("doubling: n -> total_copy, copy/n")
for n in (1_000, 10_000, 100_000, 1_000_000):
total_copy, _ = total_copy_cost_doubling(n)
print(n, total_copy, round(total_copy / n, 3))
print("additive (c=8): n -> total_copy, copy/n")
for n in (1_000, 2_000, 4_000):
total_copy, _ = total_copy_cost_additive(n, c=8)
print(n, total_copy, round(total_copy / n, 3))
Running this prints:
doubling: n -> total_copy, copy/n
1000 1023 1.023
10000 16383 1.638
100000 131071 1.311
1000000 1048575 1.049
additive (c=8): n -> total_copy, copy/n
1000 62000 62.0
2000 249000 124.5
4000 998000 249.5
The doubling column stays in a narrow band (roughly 1 to 1.6) no matter how large n gets, which is the empirical signature of O(1) amortized cost. The additive column roughly doubles every time n doubles, which is the empirical signature of the amortized cost growing linearly with n, i.e., O(n) per append on average.
Trade-offs & pitfalls
- A larger growth factor means fewer resizes and a lower amortized constant, but more wasted memory sitting unused right after a resize (up to nearly half the array, for doubling).
- A growth factor close to 1 keeps memory tight but causes frequent resizes and a larger amortized constant; taken to the extreme (fixed additive growth), it loses the O(1) guarantee altogether.
- Amortized O(1) is a statement about the long-run average, not a promise that every individual call is fast: a single append can still legitimately cost O(n) when it happens to trigger the resize. That distinction matters in a hot loop with a strict per-call latency budget, where an occasional O(n) spike may be unacceptable even though the average is fine.
- Shrinking on removal needs the same care: if you shrink back to exactly the current size whenever the array isn't full, an alternating pattern of append-then-remove near that boundary can trigger a resize on almost every operation (grow/shrink thrashing). The standard fix is asymmetric thresholds, for example only shrinking once usage drops to a quarter of capacity, and halving (not shrinking all the way to fit) when it does.
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.
Explain what a binary heap is, how min-heap and max-heap differ, and the time complexity of insert, peek, and extract-min/max. Then say when you would reach for a heap over a balanced BST or a plain hash table for the same job.
Sample Answer
Direct answer
A binary heap is a complete binary tree (every level full except possibly the last, which fills left to right) stored compactly in an array. A min-heap keeps every parent less than or equal to its children, so the root is always the minimum; a max-heap keeps every parent greater than or equal to its children, so the root is always the maximum. Insert and extract-min/max both cost O(logn) because each only has to fix a single root-to-leaf path, while peek is O(1) since the answer always sits at the root. Reach for a heap over a balanced binary search tree (BST) or a plain hash table specifically when the operation you actually need is "give me the current min or max, repeatedly, while other items keep arriving": a heap does that with a simpler structure and lower constant factors than a full BST, and a hash table can't do it at all without a full scan.
Structured elaboration
Array representation and core operations (0-indexed; for a node at index i, its children sit at 2i+1 and 2i+2)
- Insert: append the new value at the next free array slot, then "sift up", swapping it with its parent while the heap property is violated. Time O(logn) (tree height), space O(1) auxiliary.
- Peek: return the root value directly. Time O(1).
- Extract-min/max: read the root, move the last array element into the root position, shrink the array by one, then "sift down" from the root, swapping with the smaller (or larger) child until the heap property holds. Time O(logn).
- Build-heap (heapify) from an existing array: run sift-down starting from the last non-leaf node back to the root, not one insert at a time. This costs O(n) total, not O(nlogn): most nodes sit near the bottom of the tree and only need a short sift-down, and the sum of sift-down work across all levels is a convergent series bounded by O(n), tighter than treating it as n separate O(logn) inserts.
Heap versus balanced BST versus hash table
| Need | Heap | Balanced BST | Hash table |
|---|---|---|---|
| Current min/max in O(1) | Yes (peek) | Only if a pointer to the extreme node is cached separately | No |
| Insert | O(logn) | O(logn) | O(1) average |
| Extract min/max | O(logn) | O(logn) | O(n) (full scan) |
| Arbitrary key lookup | O(n) (no ordering by key beyond the root) | O(logn) | O(1) average |
| Sorted / in-order traversal | O(nlogn) (repeated extraction) | O(n) (already ordered) | Not supported |
Use a heap when you repeatedly need the current best item and nothing else about ordering; use a BST when you also need range queries, in-order traversal, or predecessor/successor lookups; use a hash table when you only need arbitrary-key existence or lookup and never need the min, max, or any ordering.
Worked example
A concrete use of a min-heap of bounded size k to track the top-k largest values in a stream: push each new value; once the heap holds k items, only replace the root (the current smallest of the kept set) if the new value is larger.
import heapq
def top_k_largest(nums: list[int], k: int) -> list[int]:
heap: list[int] = []
for x in nums:
if len(heap) < k:
heapq.heappush(heap, x)
elif x > heap[0]:
heapq.heapreplace(heap, x)
return sorted(heap, reverse=True)
if __name__ == "__main__":
nums = [7, 2, 9, 4, 1, 8, 3, 10, 5, 6]
print(top_k_largest(nums, 3))
Running this prints [10, 9, 8]: the heap only ever holds the 3 largest values seen so far, each of the other 7 values is checked against the current smallest kept value (the root) in O(1) and, if larger, replaces it in O(logk), for a total cost of O(mlogk) across m input values.
Trade-offs & pitfalls
- Inserting n elements one at a time into an empty heap costs O(nlogn) total; heapify builds the same final structure in O(n). Both produce a valid heap, only the construction cost differs, and conflating the two is a common mistake.
- A heap does not support efficient arbitrary-key lookup or a "decrease this specific key's priority" operation without extra bookkeeping (an auxiliary map from key to its current array position); this matters for algorithms like Dijkstra's shortest-path algorithm that rely on decrease-key.
- k-ary heaps (each node has k children instead of 2) trade a shallower tree, so insert and decrease-key touch fewer levels, for a more expensive sift-down, since each step now compares against k children instead of 2; they help when insert/decrease-key frequency dominates extraction frequency.
- Duplicate keys are allowed by the heap property; the ordering among equal keys is unspecified and shouldn't be relied upon.
Given an array of integers and a target value, find the indices of two numbers that add up to the target, in a single pass and without assuming the array is sorted. What is the best achievable time complexity, and what do you trade for it?
Sample Answer
Direct answer
Walk the array once while maintaining a hash map from value to the index where you first saw it. For each element x at index i, check whether target - x is already a key in the map before inserting x itself; if it is, you've found the pair in that same pass. That gives O(n) average time using O(n) extra space for the map, which is the best achievable without assuming the array is sorted, since you need to have looked at the data at least once to guarantee you haven't missed a valid pair; what you trade for that speed is the extra memory the map uses.
Approach
- Keep a dictionary
seenmapping each value to the first index it appeared at. - For each index
iand valuex, computeneed = target - xand checkseenforneedbefore addingxtoseen; checking first is what prevents pairing an element with itself whentarget == 2 * x. - Return the pair of indices the moment a match is found; a single pass suffices.
from typing import List, Optional
def two_sum(nums: List[int], target: int) -> Optional[List[int]]:
"""Returns indices [i, j] such that nums[i] + nums[j] == target.
Average O(n) time, O(n) space."""
seen: dict[int, int] = {}
for i, x in enumerate(nums):
complement = target - x
if complement in seen:
return [seen[complement], i]
if x not in seen:
seen[x] = i
return None
if __name__ == "__main__":
print(two_sum([2, 7, 11, 15], 9)) # [0, 1]
print(two_sum([3, 3], 6)) # [0, 1]
print(two_sum([1, 2, 3], 100)) # None
Running this prints [0, 1], [0, 1], and None. In the second case, target 6 with nums = [3, 3]: at i=0, need=3 isn't in seen yet, so 3 is stored at index 0; at i=1, need=3 is now in seen, giving [0, 1], correctly using two distinct indices for the same value rather than pairing index 0 with itself.
Key points
- Checking for the complement before inserting the current value is what stops the algorithm from matching an element with itself when
targetequals twice that element's value. - "Average" O(n), not worst-case, is the honest label: each hash map operation is O(1) on average given a reasonably distributed hash, but an input engineered to collide against the hash function could in principle degrade individual lookups, which is a real (if unusual) concern in adversarial settings.
- The streaming variant, where you can't store the whole array up front, still needs O(n) auxiliary memory for values seen so far, since you must remember what's already been scanned; there's no way around that memory cost unless an additional constraint (like a bounded value range) lets you swap the hash map for a fixed-size bitset.
Complexity
Time: O(n) average (n hash map operations, each O(1) average). Space: O(n) for the seen map.
Edge cases
- No valid pair exists: the function should signal that clearly (returning
Nonehere, or raising, depending on the calling convention) rather than silently returning a wrong pair. - Duplicate values that sum to the target: handled correctly by storing the first occurrence and checking the complement before inserting the current value.
- Negative numbers: work without special-casing, since dictionary keys and arithmetic on
target - xdon't assume non-negative values. - An empty array or an array with fewer than two elements: no valid pair is possible.
Unlock Full Question Bank
Get access to all 29 Algorithmic Problem-Solving and Data Structure Selection interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.