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.
Implement a fixed-size circular (ring) buffer supporting enqueue, dequeue, peek, isEmpty, and isFull, all in O(1), backed by a single fixed-size array (no resizing, no shifting elements). Explain how you distinguish the full state from the empty state when the head and tail indices coincide.
Sample Answer
Direct answer
Back the buffer with a single fixed-size array plus a head index (next slot to read), a tail index (next slot to write), and an explicit count of stored elements; advance head and tail with modulo arithmetic so they wrap around the array instead of growing unbounded. The count is what distinguishes full from empty when head equals tail: head==tail with count==0 is empty, and head==tail with count==capacity is full, which is exactly the ambiguous case that arises because a fixed-size array wraps the same index for both states.
Structured elaboration
Why head==tail is ambiguous without extra state
After capacity-many enqueues with no dequeues, tail has wrapped all the way back around to equal head: the buffer is full. But before anything has ever been enqueued, head also equals tail: the buffer is empty. Comparing head and tail alone cannot tell these two states apart, since both produce head==tail. Two standard fixes exist:
- Keep an explicit count (as below): full is
count == capacity, empty iscount == 0, and head==tail is irrelevant to the check. - Reserve one slot: never let the buffer report full until only one slot remains empty, so full is
(tail + 1) % capacity == headand empty ishead == tail. This avoids a separate counter at the cost of one unusable slot.
Operations, all O(1)
enqueue(value): reject if full; otherwise write attail, advancetail = (tail + 1) % capacity, increment count.dequeue(): reject if empty; otherwise read athead, advancehead = (head + 1) % capacity, decrement count.peek(): reject if empty; otherwise read atheadwithout advancing anything.is_empty()/is_full(): direct comparisons against the count.
Worked example
class RingBufferFull(Exception):
pass
class RingBufferEmpty(Exception):
pass
class RingBuffer:
"""
Fixed-capacity circular buffer backed by a single preallocated list.
All operations O(1) time, O(capacity) space.
Distinguishes full from empty with an explicit count (no wasted slot).
"""
def __init__(self, capacity: int):
if capacity <= 0:
raise ValueError("capacity must be positive")
self._buf: list[object] = [None] * capacity
self._capacity = capacity
self._head = 0 # next slot to dequeue from
self._tail = 0 # next slot to enqueue into
self._count = 0
def is_empty(self) -> bool:
return self._count == 0
def is_full(self) -> bool:
return self._count == self._capacity
def enqueue(self, value: object) -> None:
if self.is_full():
raise RingBufferFull()
self._buf[self._tail] = value
self._tail = (self._tail + 1) % self._capacity
self._count += 1
def dequeue(self) -> object:
if self.is_empty():
raise RingBufferEmpty()
value = self._buf[self._head]
self._buf[self._head] = None
self._head = (self._head + 1) % self._capacity
self._count -= 1
return value
def peek(self) -> object:
if self.is_empty():
raise RingBufferEmpty()
return self._buf[self._head]
if __name__ == "__main__":
rb = RingBuffer(3)
rb.enqueue("a")
rb.enqueue("b")
rb.enqueue("c")
print("full:", rb.is_full())
print("peek:", rb.peek())
print("dequeue:", rb.dequeue())
rb.enqueue("d") # wraps into the slot freed by "a"
drained = [rb.dequeue() for _ in range(3)]
print("drained order:", drained)
print("empty:", rb.is_empty())
Running this prints:
full: True
peek: a
dequeue: a
drained order: ['b', 'c', 'd']
empty: True
After enqueueing "a", "b", "c" into a capacity-3 buffer, it reports full and peek/dequeue both correctly return "a" first (FIFO, first-in first-out order). Dequeuing "a" frees the slot at index 0; enqueueing "d" then wraps tail back to index 0, reusing that freed slot rather than growing the array. Draining the remaining three elements returns them in the order they were inserted: "b", "c", "d", confirming the wraparound did not disturb ordering.
Complexity
Time: O(1) for enqueue, dequeue, peek, is_empty, and is_full. Space: O(capacity), fixed at construction and never resized.
Edge cases
- Requesting a non-positive capacity is rejected at construction; a zero-capacity buffer can never hold anything meaningfully.
- Enqueue on a full buffer and dequeue or peek on an empty buffer both raise rather than silently corrupting state or returning a stale value.
- Wraparound at the exact array boundary (tail or head going from
capacity - 1back to0) is the core case the modulo arithmetic must get right; it is worth tracing by hand once, as in the worked example above. - A single-element capacity (capacity=1) still needs enqueue/dequeue/peek to behave correctly; it is a good minimal stress case for wraparound logic.
Trade-offs & pitfalls
The count-based design and the reserved-slot design are both correct and both O(1); the count-based version uses one extra integer but keeps the full array usable, while the reserved-slot version needs no extra counter but permanently wastes one slot of capacity. A common wrong turn is trying to distinguish full from empty using only head and tail without either fix, which silently produces a buffer that reports empty immediately after becoming full (or vice versa) the moment head and tail happen to coincide. Another common gap, in the producer/consumer framing this question absorbs, is forgetting that concurrent producers and consumers touching head, tail, and the array simultaneously need explicit synchronization (a lock, or lock-free atomic operations for the single-producer single-consumer case); the plain implementation above is correct only for a single thread, or for multiple threads coordinated externally. A related, absorbed framing: a deque that supports push and pop at both ends (not just enqueue at the tail and dequeue at the head) is the same fixed-capacity wraparound array, just allowing insertion and removal at either the head or the tail index; every operation is still O(1) against the fixed capacity. If that deque is also allowed to grow when full, by allocating a larger array and copying everything across (doubling being the usual choice), the cost analysis of those occasional resizes is the identical amortized argument used for a growable dynamic array: expensive individual resizes, but O(1) amortized per push or pop over the whole sequence.
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.
Design a counter that reports how many events happened in the last W seconds (or the last k events), as new events keep arriving. A plain running total cannot expire old events; explain the structure you would use so both recording a new event and asking for the current count stay cheap.
Sample Answer
Direct answer
Store only the timestamps that currently fall inside the window in a deque (a double-ended queue supporting O(1) push and pop from both ends), rather than recomputing a count from the full event history. Each new event is appended to the back; each query pops expired timestamps off the front until only in-window events remain, then reports the deque's length.
Structured elaboration
Approach
- A plain running total can be incremented on arrival, but it has no way to know which additions have aged out of the last W seconds, so it can only grow, never correctly shrink.
- Keeping only the timestamps inside the window, instead of a total, turns "is this event still relevant" and "how many are relevant" into deque operations: pop from the front while the oldest entries are older than the window allows, then read the length.
- Because timestamps only ever arrive in non-decreasing order, once an entry is popped off the front for being too old, it never needs to be looked at again. Each entry is pushed exactly once and popped at most once over its whole lifetime in the structure.
from collections import deque
class WindowCounter:
def __init__(self, window_seconds):
self.window = window_seconds
self.q = deque() # event timestamps currently inside the window, oldest first
def record(self, t):
"""Record an event at time t. Timestamps must arrive non-decreasing."""
self.q.append(t)
def count(self, now):
"""Return how many recorded events fall in (now - window, now]."""
cutoff = now - self.window
while self.q and self.q[0] <= cutoff:
self.q.popleft()
return len(self.q)
Key points
dequegives O(1) append and popleft, unlike a plain list where popping the front is O(n).- The "pop expired from the front" step, run on every record or query, is what keeps memory bounded to just the events inside the window.
- This only works because input timestamps are non-decreasing; out-of-order arrivals would need a different structure.
Worked example
window_seconds = 10, recording and querying at the same moment as each event arrives, in order [0, 3, 5, 9, 12, 15]:
wc = WindowCounter(window_seconds=10)
for t in [0, 3, 5, 9, 12, 15]:
wc.record(t)
print(f"t={t}: count={wc.count(t)}")
prints:
t=0: count=1
t=3: count=2
t=5: count=3
t=9: count=4
t=12: count=4
t=15: count=3
At t = 12, the cutoff is 12 - 10 = 2, so the timestamp 0 (which is <= 2) is popped, leaving {3, 5, 9, 12}, a count of 4. At t = 15, the cutoff is 5, so timestamps 3 and 5 (both <= 5) are popped, leaving {9, 12, 15}, a count of 3.
Trade-offs & pitfalls
Complexity
Time: amortized O(1) per record or count call. "Amortized" here means that although a single count call could in principle pop many expired entries at once, each timestamp is pushed once and popped at most once over the structure's whole lifetime, so total work across n calls is O(n), averaging to O(1) per call even though any single call's worst case is O(n).
Space: O(k), where k is the number of events currently inside the window, bounded by the arrival rate times the window length rather than by total history.
Edge cases
- No events yet: the deque is empty,
countreturns 0. - Window smaller than the gap between consecutive events: the deque may hold 0 or 1 entries at a time.
- A burst of many events at the same instant: all are held until they age out together.
This only works if timestamps are guaranteed non-decreasing, as from a single writer or a single ordered stream. If events can arrive out of order (merged from multiple producers, or delayed in transit), the front-popping logic breaks, since an old event could arrive after entries that looked older have already been discarded. That calls for a different structure: a min-heap keyed on timestamp, or a fixed-size time-bucketed histogram (a small array of counters, one per sub-interval, rotated as time advances) for approximate counting in bounded memory regardless of burst size.
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.
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.
Unlock Full Question Bank
Get access to all 32 Algorithmic Problem-Solving and Data Structure Selection interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.