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.
Given a set of vertical lines at integer x-positions with given heights, find the two lines that, together with the x-axis, trap the most water between them. Solve it in O(n) time using two pointers, and explain the greedy argument for why you can safely move the shorter side inward without missing the optimal answer.
Sample Answer
Direct answer
Start with two pointers at the far-left and far-right lines and compute the area between them as the width times the shorter of the two heights, since the shorter line is what actually limits how much water the pair can hold. Then repeatedly move whichever pointer marks the shorter line one step inward, tracking the best area seen. This is safe because keeping the shorter line fixed and moving the taller one inward can only shrink the width while the limiting height stays the same or gets worse, so that move can never beat the current area; moving the shorter line is the only move that has any chance of finding a taller line and thus a larger limiting height.
Approach
- Initialize
left = 0andright = len(height) - 1. - At each step, compute
area = min(height[left], height[right]) * (right - left)and update the best area seen. - Move the pointer at the shorter height inward (
left += 1orright -= 1); if the two heights are equal, either pointer can move. - Stop when
left == right.
from typing import List
def max_area(height: List[int]) -> int:
"""Two-pointer O(n) time, O(1) space solution."""
left, right = 0, len(height) - 1
best = 0
while left < right:
h = min(height[left], height[right])
best = max(best, h * (right - left))
if height[left] < height[right]:
left += 1
else:
right -= 1
return best
if __name__ == "__main__":
print(max_area([1, 8, 6, 2, 5, 4, 8, 3, 7])) # 49
print(max_area([1, 1])) # 1
print(max_area([4, 3, 2, 1, 4])) # 16
Running this prints 49, 1, 16. For [1, 8, 6, 2, 5, 4, 8, 3, 7], the best area of 49 comes from index 1 (height 8) and index 8 (height 7): width 8−1=7 times limiting height min(8,7)=7 gives 49, and no other pair in that array beats it.
Key points
- The greedy step only works because the pointer you leave behind (the taller one) was never the bottleneck for the current pair, so discarding it costs nothing you could have used; discarding the shorter one instead would throw away the only pointer that could have found something taller.
- Equal heights at both pointers: either pointer can move; the tie means both sides are equally the "shorter" one for that comparison.
- In a fixed-width-integer language (Java, C++),
height * widthcan overflow a 32-bit integer for very large inputs; use a 64-bit accumulator for the area. Python integers don't have this issue, but it's a real production concern in typed languages.
Complexity
Time: O(n), a single pass with the two pointers converging. Space: O(1), only the two pointers and a running best value.
Edge cases
- Fewer than two lines: no container is possible, so the answer is 0.
- All heights equal: every pair's limiting height is the same, so the widest pair (the two endpoints) wins.
- A height of 0 at some position contributes an area of 0 whenever it's one of the two chosen lines, which is harmless, just never optimal.
- This two-pointer approach only finds the best area between two chosen lines; it does not generalize directly to the harder "water trapped above every bar" version of this problem (where interior bars can also trap water above them), since that variant needs to track a running maximum height from the left and from the right at every position, not just a single global best between two outer lines. It's a natural harder extension of the same converging-pointer idea, but with per-position bookkeeping added on top.
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.
Implement one classic sort algorithm from scratch (your choice of quicksort with in-place partitioning, merge sort, or counting sort for small-range integers). Explain why you chose that one for the input characteristics given, and what your partition or merge step's complexity is.
Sample Answer
Direct answer
For this kind of general, range-unknown input, I would implement randomized in-place quicksort: pick a uniformly random pivot at each partition step (to defeat adversarial or already-sorted inputs), partition with Lomuto's scheme, and always continue on the smaller of the two resulting partitions while deferring the larger one, which bounds recursion/stack depth to O(log n). Quicksort is the right default here over merge sort (which needs O(n) extra space) or counting sort (which needs a small, known key range).
Structured elaboration
Why quicksort for this input: it sorts in place (O(log n) extra memory instead of merge sort's O(n)), its sequential partition scan is cache-friendly and typically fastest in practice, and it makes no assumption about the range of the keys, unlike counting sort.
Partition step (Lomuto): move the pivot to the end, then walk the range once, swapping any element smaller than the pivot into a growing "less-than" prefix; finally swap the pivot into its correct final position.
Random pivot selection removes the classic O(n^2) worst case that a fixed first/last-element pivot suffers on already-sorted or reverse-sorted input.
import random
def quicksort_inplace(a: list[int], seed: int = 0) -> None:
"""
Randomized in-place quicksort with Lomuto partitioning.
Always recurses on the smaller side and loops on the larger side
(via an explicit stack) to bound auxiliary depth at O(log n).
"""
rng = random.Random(seed)
def partition(lo: int, hi: int) -> int:
pivot_idx = rng.randint(lo, hi)
a[pivot_idx], a[hi] = a[hi], a[pivot_idx]
pivot = a[hi]
store = lo
for i in range(lo, hi):
if a[i] < pivot:
a[store], a[i] = a[i], a[store]
store += 1
a[store], a[hi] = a[hi], a[store]
return store
lo, hi = 0, len(a) - 1
stack = [(lo, hi)]
while stack:
lo, hi = stack.pop()
while lo < hi:
p = partition(lo, hi)
left_size = p - lo
right_size = hi - p
if left_size < right_size:
stack.append((p + 1, hi))
hi = p - 1
else:
stack.append((lo, p - 1))
lo = p + 1
data = [5, 2, 9, 1, 5, 6, 3, 8, 2, 0, -4, 7]
quicksort_inplace(data, seed=42)
print(data)
data2 = []
quicksort_inplace(data2, seed=42)
print(data2)
data3 = [1]
quicksort_inplace(data3, seed=42)
print(data3)
Output:
[-4, 0, 1, 2, 2, 3, 5, 5, 6, 7, 8, 9]
[]
[1]
Key points: continuing inline on the smaller partition (via the loop) while pushing only the larger one onto the explicit stack is what bounds the stack's maximum size to O(log n), since each level you push at least halves relative to its parent range.
Worked example
The input [5, 2, 9, 1, 5, 6, 3, 8, 2, 0, -4, 7] (note the repeated values 5 and 2) sorts correctly to [-4, 0, 1, 2, 2, 3, 5, 5, 6, 7, 8, 9] with seed 42, as shown in the run above; the duplicate values are handled fine by Lomuto's plain "<" comparison, since equal elements simply land in the "not less than pivot" partition without needing any special casing.
Complexity
\text{space: } O(\log n) \text{ average}$$, bounded by the smaller-first recursion rule (without it, worst-case stack depth is $$O(n)$$). The partition step itself is $$O(hi - lo)$$, linear in the size of the range being partitioned, since Lomuto's scan touches every element in that range exactly once. ### Edge cases - **Empty input** (`[]`): the initial stack holds `(0, -1)`, so `lo < hi` is false immediately and the loop body never runs; sorts to `[]`, as shown in the run above. - **Single-element input** (`[1]`): `(0, 0)`, `lo < hi` is false immediately, returns unchanged. - **All-duplicate or many-duplicate input**: Lomuto's plain "<" test sends every equal element to the "not less than pivot" side, degrading toward $$O(n^2)$$; see "Many duplicates" below for the fix. - **Already-sorted or reverse-sorted input**: random pivot selection specifically defeats the classic $$O(n^2)$$ worst case that a fixed-pivot quicksort suffers on this input shape. ## Trade-offs & pitfalls - **Worst case**: O(n^2) is astronomically unlikely with a random pivot, since it would require an adversary who can predict your random seed, not just an adversary who controls input order. - **Stack depth**: the smaller-first rule guarantees O(log n) auxiliary depth even in the worst case; without it, an adversarial input can force O(n) recursion depth. - **Many duplicates**: Lomuto's plain "<" comparison degrades toward O(n^2) when most elements are equal, since every element goes to one side of the partition; 3-way (Dutch national flag) partitioning fixes this by giving equal elements their own middle section. - **Not stable**: equal elements can be reordered relative to each other; reach for merge sort instead if stability matters. - **When to prefer the alternatives**: counting sort wins when keys are small non-negative integers in a known bounded range (O(n+k) time, no comparisons at all); merge sort wins when guaranteed worst-case O(n log n) time or stability matters and the O(n) extra memory is affordable, such as external/on-disk sorting or sorting linked lists where in-place partitioning is awkward.When would you reach for a hash map over an ordered structure like a balanced BST or skip list, and when does giving up hash-map speed for guaranteed ordering (range scans, deterministic iteration, sorted output) actually pay off? Give a concrete case for each side.
Sample Answer
Direct answer
Reach for a hash map whenever you need the fastest average lookup, insert, and delete and do not care about the order keys come out in. Reach for an ordered structure (a balanced binary search tree, BST for short, meaning a tree kept balanced so its height stays logarithmic; or a skip list, a linked structure with multiple randomly-built "express lane" levels that gives logarithmic search without needing tree rebalancing) whenever you need range queries, sorted iteration, or predecessor/successor lookups, since a hash map fundamentally cannot answer those without scanning every entry.
Structured elaboration
| Hash map | Ordered structure (BST / skip list) | |
|---|---|---|
| Lookup / insert / delete | O(1) average, O(n) worst case | O(logn) average and worst case (balanced BST); O(logn) expected (skip list) |
| Min / max | not supported directly | O(logn) |
| Predecessor / successor | not supported directly | O(logn) |
| Range query (all keys in [lo, hi]) | requires a full scan | O(logn+k) for k results |
| Iteration order | unspecified (or insertion order only for specific implementations) | ascending key order |
Concrete case where a hash map wins: an in-memory cache keyed by an exact request signature, for example caching a computed response by its full input hash, where every lookup is "does this exact key exist" and there is no notion of "keys near this one" that would ever be queried. The O(1) average lookup directly minimizes latency, and there is nothing to give up, since ordering was never needed.
Concrete case where giving up hash-map speed pays off: a scheduler that needs "the next event after this timestamp." That is a successor query, unsupported by a hash map without scanning every key, but native to an ordered structure in O(logn). Trading average-case O(1) for guaranteed O(logn) is a clear win here because the operation the hash map cannot do at all is the operation the system needs on every scheduling step.
Trade-offs & pitfalls
A hash map's worst-case degrades to O(n) under pathological collisions, though modern implementations mitigate this with randomized hash seeding; an ordered structure's O(logn) is a hard guarantee regardless of key distribution, which matters if an adversary can influence which keys get inserted (for example, in a public-facing API). A common mistake is reaching for an ordered structure "just in case sorted output is needed later," which pays the O(logn) tax on every single operation for a benefit that may never be used; the right trigger is a concrete, recurring range or predecessor/successor query in the actual access pattern, not a hypothetical one. It is also common to forget that some hash map implementations preserve insertion order as an incidental property (not a sorted, comparison-based order), which is a much weaker guarantee than a true ordered structure's ability to iterate or range-query by key value.
Design a data structure that supports insert(value), remove(value), and getRandom() so that every currently-stored value is equally likely to be returned, with all three operations running in expected O(1) time. A hash set alone gives you O(1) insert/remove but not uniform O(1) random access; explain what you add to fix that.
Sample Answer
Direct answer
Keep a resizable array of the stored values plus a hash map from value to that value's index in the array. Insert appends to the array in O(1); getRandom picks a uniformly random array index in O(1); the trick is delete, which must not leave a gap: swap the removed value with the array's last element, update that moved element's index in the hash map, then pop the last slot off in O(1).
Structured elaboration
values: an array of the currently stored values, with no gaps.index_of: hash map from value to its current position invalues.
insert(val): if val is already in index_of, return false. Otherwise append it to values and record its index.
remove(val): if val is absent, return false. Otherwise look up its index, overwrite that slot with the array's last element (updating that moved element's entry in index_of to the vacated index), then pop the array's last slot and delete val from index_of. Because the moved element simply changes which index it lives at, and every array slot is always occupied by exactly one live value, no gap is ever created and no shifting of the remaining elements is needed.
getRandom(): choose a uniformly random integer index in [0, len(values)) and return values[that index]. Since each stored value occupies exactly one slot and slots are chosen uniformly, every value has equal probability of being returned.
The reason a plain hash set cannot support getRandom in O(1) is that hash tables give you no way to address "the k-th element" directly: you would need to walk buckets, which is not O(1) and not uniform once buckets have different chain lengths. The array gives you that direct O(1) addressing that a hash table structurally lacks.
Worked example
import random
class RandomizedSet:
def __init__(self):
self.index_of: dict[int, int] = {}
self.values: list[int] = []
def insert(self, val: int) -> bool:
if val in self.index_of:
return False
self.index_of[val] = len(self.values)
self.values.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.index_of:
return False
idx = self.index_of[val]
last_val = self.values[-1]
self.values[idx] = last_val
self.index_of[last_val] = idx
self.values.pop()
del self.index_of[val]
return True
def get_random(self) -> int:
return random.choice(self.values)
random.seed(42)
rs = RandomizedSet()
print(rs.insert(1))
print(rs.insert(2))
print(rs.insert(3))
print(rs.remove(2)) # swaps 3 into index 1
print(rs.values)
print(rs.get_random())
print(rs.get_random())
Running this (CPython's random module, seeded) prints:
True
True
True
True
[1, 3]
1
1
Key points
- The swap-with-last trick is what keeps delete O(1): it avoids shifting every element after the removed one.
- Uniformity comes from the array having no gaps:
random.choiceover indices is exactly a uniform choice over the stored values.
Complexity
O(1) averagefor insert, remove, and getRandom; O(n) space for the array and hash map together.
Edge cases
- Removing the last element in the array: the "swap with last" step is swapping an element with itself, which is harmless.
getRandomon an empty structure has no valid answer; guard it explicitly (raise, or document as undefined behavior) rather than lettingrandom.choicethrow an unhandled exception on an empty list.
Trade-offs & pitfalls
The most common mistake is deleting by shifting all elements after the removed index, which is correct but O(n), defeating the point. A second common mistake is deleting by using values.remove(val) in Python, which internally does that same O(n) scan-and-shift. The design absorbs a lighter-weight sibling problem well: an insertion-order-preserving set (for example, deduplicating items in a shopping cart while keeping display order) uses the same "array plus hash map of positions" composition, but it cannot use the swap-with-last trick, because swapping would destroy the insertion order it is trying to preserve. That variant instead needs either a tombstone marker left in place (with periodic compaction) or a doubly linked list plus hash map (the same structure used for an LRU cache), trading away the O(1) swap-delete for order preservation.
Unlock Full Question Bank
Get access to all Algorithmic Problem-Solving and Data Structure Selection interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.