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.
You are given a list of courses and prerequisite pairs: to take course A you must first take course B. Determine whether it is possible to finish all courses, and if so, produce one valid order to take them in. What should your algorithm do if the prerequisites contain a cycle?
Sample Answer
Direct answer
Model the courses as a directed graph where an edge from a prerequisite B to a course A means "B must come before A", then run Kahn's algorithm: repeatedly take any course whose remaining prerequisite count (its indegree) is zero, add it to the order, and decrement the indegree of everything it unlocks. If every course gets processed this way, the resulting order is valid. If the queue empties while courses still have a nonzero indegree, those courses form a cycle, a prerequisite loop that can never be satisfied, and finishing all courses is impossible.
Approach
- Build an adjacency list (prerequisite to course) and an indegree array (how many unprocessed prerequisites each course still has).
- Seed a queue with every course that already has indegree zero.
- Repeatedly pop a course, append it to the output order, and for every course it unlocks, decrement that course's indegree; if it hits zero, enqueue it.
- If the final order's length equals the number of courses, it's a valid full order; otherwise the remaining, never-enqueued courses are exactly the ones stuck in a cycle.
from collections import deque
from typing import List, Tuple
def find_order(num_courses: int, prerequisites: List[Tuple[int, int]]) -> List[int]:
"""prerequisites: list of (course, prereq) pairs meaning 'course'
depends on 'prereq'. Returns a valid order, or [] if a cycle makes
finishing all courses impossible."""
adj: list[list[int]] = [[] for _ in range(num_courses)]
indeg = [0] * num_courses
for course, prereq in prerequisites:
adj[prereq].append(course)
indeg[course] += 1
queue = deque(c for c in range(num_courses) if indeg[c] == 0)
order: list[int] = []
while queue:
node = queue.popleft()
order.append(node)
for nxt in adj[node]:
indeg[nxt] -= 1
if indeg[nxt] == 0:
queue.append(nxt)
return order if len(order) == num_courses else []
if __name__ == "__main__":
# course 1 needs 0, course 2 needs 0, course 3 needs 1 and 2
print(find_order(4, [(1, 0), (2, 0), (3, 1), (3, 2)]))
# cycle: 0 needs 1, 1 needs 0
print(find_order(2, [(0, 1), (1, 0)]))
Running this prints [0, 1, 2, 3] for the first case (course 0 has no prerequisites, unlocks 1 and 2, which both unlock 3) and [] for the second (a two-course cycle where neither course ever reaches indegree zero).
Key points
- The indegree count is exactly "how many prerequisites this course is still waiting on"; a course only becomes eligible once that count hits zero.
- Multiple valid orders can exist whenever more than one course is simultaneously eligible; if a canonical, reproducible order matters (for example a deterministic build or test replay), swap the queue for a min-heap to always take the smallest eligible course id next, which costs O(logk) per pop instead of O(1), where k is the number of currently eligible courses.
- A directed acyclic graph (DAG) is the name for the acyclic case that always has at least one valid topological order; the moment a cycle exists, no such order can exist for the courses on that cycle.
Complexity
Time: O(V+E) where V is the number of courses and E is the number of prerequisite pairs (each course and each edge is processed exactly once). Space: O(V+E) for the adjacency list and indegree array.
Edge cases
- Disconnected components or isolated courses (no prerequisites and nothing depends on them) are scheduled immediately, since their indegree starts at zero.
- A course listed as its own prerequisite is a one-node cycle and is caught by the same length check.
- Duplicate prerequisite pairs inflate the indegree count but don't change correctness, since the count still reaches zero at the same logical point (one extra decrement per duplicate, which the duplicate edge itself supplies).
- An empty prerequisite list means every order of the courses is valid.
- Checking only "did the queue run empty" without also checking that the output length equals the course count is the most common bug: a graph can have one small cycle alongside many unrelated, fully resolvable courses, and skipping the length check silently returns an incomplete, invalid order.
Given an array and a window size k, return the maximum value in every window of size k as it slides across the array, in O(n) total time (not O(n*k)). Explain what a monotonic deque gives you here that a plain heap-per-window would not.
Sample Answer
Direct answer
Maintain a deque (double-ended queue) of array indices whose corresponding values are strictly decreasing from front to back; the front always holds the index of the current window's maximum. Because every index enters and leaves the deque at most once, the whole scan costs O(n) time and O(k) extra space, not O(nk). This is the key advantage over a plain re-scan of every window, and over a max-heap seeded per window.
Structured elaboration
Why a naive re-scan is slow. Scanning all k elements for every one of the roughly n windows costs O(nk), which is quadratic-ish for k proportional to n.
The monotonic deque invariant. Values at the indices stored in the deque, read front to back, are strictly decreasing. Two maintenance rules keep this true:
- When a new value x arrives, pop from the back any index whose value is less than or equal to x. Those entries can never again be the answer: x is both later in the array and at least as large, so it dominates them for every future window that could still contain them.
- When the index at the front has slid outside the current window (its index is at or before
i - k), pop it from the front.
After both rules run for position i, the front of the deque is the index of the maximum value inside the current window.
Why a heap-per-window is worse. A max-heap of (value, index) pairs gives you the maximum in O(logk), but a heap has no cheap way to remove a specific entry sitting in the middle once it slides out of the window; only the root is efficiently removable. The usual workaround is lazy deletion: leave stale entries in the heap and discard them only when they surface at the top. That still costs O(nlogk) overall, and it requires carrying the index alongside the value just to check staleness, which the monotonic deque never needs because it never holds a dominated entry in the first place.
The same window shape, a different comparator (moving sum/average). If you swap "maximum" for "sum" or "average" over the same sliding window, the eviction and maintenance shape is identical (add the newest element, evict the oldest), but you no longer need the deque's monotonic bookkeeping at all: a running total lets you add the new value and subtract the value leaving the window in O(1) per step, because a sum is directly cancelable (subtracting an old term removes exactly its contribution) while a maximum is not (removing an old value does not tell you what the next-largest value is). That is the structural reason the maximum needs the deque and the sum does not.
Worked example
from collections import deque
def max_sliding_window(nums: list[int], k: int) -> list[int]:
dq: deque[int] = deque() # indices; values strictly decreasing front-to-back
result = []
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x:
dq.pop()
dq.append(i)
if dq[0] <= i - k:
dq.popleft()
if i >= k - 1:
result.append(nums[dq[0]])
return result
if __name__ == "__main__":
nums = [1, 3, -1, -3, 5, 3, 6, 7]
print(max_sliding_window(nums, 3))
Running this prints [3, 3, 5, 5, 6, 7]. Trace the first few steps by hand: at i=0 (value 1) the deque holds [0]; at i=1 (value 3), 3 dominates 1 so index 0 is popped from the back, leaving [1]; at i=2 (value -1), -1 does not dominate 3, so it is simply appended, giving [1, 2], and since the window (size 3) is now full, the front index 1 (value 3) is reported.
Complexity
Time: O(n). Each index is pushed onto the deque exactly once and popped from either end at most once over the whole scan, so the total work across all n steps is bounded by a constant multiple of n, not the O(nk) of the naive re-scan.
Space: O(k) extra, since the deque holds at most k indices at any time (indices that age out of the window are evicted from the front); the n-sized output array is the required result, not extra working space.
Edge cases
- k = 1: every window is a single element, so the deque approach degenerates to returning the array unchanged.
- k equal to the array's length: the deque approach reduces to reporting a single running maximum for the one full-length window.
- Empty input array: there are no windows, so the result is an empty list and the loop body never executes.
Trade-offs & pitfalls
Storing values instead of indices in the deque is the most common bug: without the index you cannot tell when the front entry has aged out of the window. The heap-with-lazy-deletion alternative is a reasonable fallback if you only remember heaps under pressure, but it is worth naming its actual cost, O(nlogk), rather than presenting it as equivalent to the deque approach.
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.
A hash table doubles its bucket array whenever the load factor exceeds 0.75. Walk through the amortized cost of a sequence of n inserts under this policy, and explain what changes if the table must also shrink (say, halving) when occupancy drops below some threshold after deletions.
Sample Answer
Direct answer
Doubling the bucket array whenever the load factor (occupied slots divided by
total capacity) exceeds 0.75 gives O(1) amortized cost per insert: the
occasional expensive rehash (copying every element into a bigger array) is
paid for by all the cheap inserts since the last resize, and because capacity
doubles, resizes become exponentially rarer as the table grows. Adding a
symmetric shrink-on-deletion policy is only safe if the shrink threshold is
set well below the grow threshold; using the same threshold for both directions
lets an adversarial (or just unlucky) sequence of alternating inserts and
deletes near the boundary trigger a full resize on every single operation,
destroying the amortized guarantee entirely.
Structured elaboration
Amortized cost of grow-only doubling (aggregate method). Suppose the
table starts at capacity c0 and doubles (ck=2kc0) each time
size exceeds θ⋅capacity for threshold θ=0.75.
At the moment of the k-th resize, the table holds roughly
θ⋅ck−1 live elements, and a resize rehashes (copies) all of
them into the new array:
Summing the rehash cost across all resizes up to the point where the table
has grown to serve n elements is a geometric series:
So total rehashing work across all resizes is O(n), not O(nlogn)
or worse, because a geometric series is dominated by its last term. Adding
the O(1) cost of each of the n individual inserts:
Why shrinking naively breaks this. The argument above works because
resize events become rarer as capacity grows (each one "pays off" a
geometrically larger batch of prior inserts). If shrinking uses the same
threshold as growing, a table can cross the grow threshold, resize, and then
land at a load factor that is already below that same threshold, so the very
next deletion immediately triggers a shrink back down, and the next insertion
after that immediately triggers a grow again. There is no batch of cheap
operations paying for each resize anymore, every operation near that boundary
pays for a full resize.
The standard fix: hysteresis. Use two different thresholds with a gap
between them, for example grow at load factor 0.75 but only shrink once load
factor drops below roughly 0.25. This guarantees that after any resize
(grow or shrink), the table must absorb a substantial number of operations
purely from the size change alone before it can cross the other threshold and
trigger another resize, restoring the same "geometric batches pay for
resizes" argument that made grow-only doubling amortized O(1).
Worked example
Simulating exact resize behavior with pinned parameters (capacity starts at
4, size starts at 3, doubling on grow, halving on shrink) demonstrates both
failure and fix:
def simulate_thrashing(n_ops, threshold=0.75):
capacity, size, total_work, resizes = 4, 3, 0, 0
for i in range(n_ops):
if i % 2 == 0:
size += 1; total_work += 1
if size / capacity > threshold:
capacity *= 2; total_work += size; resizes += 1
else:
size -= 1; total_work += 1
if capacity > 4 and size / capacity < threshold:
capacity //= 2; total_work += size; resizes += 1
return total_work, resizes
def simulate_with_hysteresis(n_ops, grow_threshold=0.75, shrink_threshold=0.25):
capacity, size, total_work, resizes = 4, 3, 0, 0
for i in range(n_ops):
if i % 2 == 0:
size += 1; total_work += 1
if size / capacity > grow_threshold:
capacity *= 2; total_work += size; resizes += 1
else:
size -= 1; total_work += 1
if capacity > 4 and size / capacity < shrink_threshold:
capacity //= 2; total_work += size; resizes += 1
return total_work, resizes
work_t, resizes_t = simulate_thrashing(2000)
work_h, resizes_h = simulate_with_hysteresis(2000)
print("same-threshold:", work_t, resizes_t, work_t / 2000)
print("hysteresis gap:", work_h, resizes_h, work_h / 2000)
Output (verified by running this exact code):
same-threshold: 9000 2000 4.5
hysteresis gap: 2004 1 1.002
With a single shared threshold, all 2000 alternating operations trigger a
resize (2000 resizes for 2000 operations, amortized 4.5 units of work per
operation for this small table); with a 0.75/0.25 hysteresis gap, only 1
resize happens across all 2000 operations, and amortized cost settles at
almost exactly 1.0, the O(1) result the design is supposed to guarantee. The
gap between grow and shrink thresholds is what restores amortized O(1) once
deletions are allowed to trigger shrinking.
Trade-offs & pitfalls
- The failure mode above gets worse, not better, at scale: the per-resize
cost is proportional to the table's current size, so the same
shared-threshold thrashing pattern on a table with 100,000 capacity and
75,000 elements turns every operation into a resize costing roughly 75,000
units of work, an amortized cost of O(n) per operation instead of
O(1), which is the whole point of the doubling scheme defeated. - Hysteresis is not free: keeping the shrink threshold well below the grow
threshold means the table tolerates more "wasted" empty capacity before
shrinking (at a 0.25 shrink threshold, the table can be using as little as
a quarter of its capacity before it shrinks), a deliberate memory-versus-
resize-frequency trade-off, not a way to avoid the trade-off entirely. - A related but distinct pitfall is choosing a shrink factor that is too
aggressive relative to the grow factor (for example, growing by 2x but
shrinking all the way back to the smallest possible size instead of by a
matching factor); this can reintroduce the same thrashing risk in a
different shape if the shrunk table is immediately close to its own grow
threshold again.
Given a list of meeting time intervals, find the minimum number of rooms (or servers) needed so that no two overlapping meetings share one. Explain why sorting start and end times separately (or a heap of active end times) gets you there, and how this differs from the plain merge-overlapping-intervals problem.
Sample Answer
Direct answer
Sort meetings by start time, and track the end times of currently occupied rooms in a min-heap (a binary heap ordered so the smallest element is always at the root, giving O(logn) push and pop). For each meeting, if the room that frees earliest already ended at or before this meeting's start, reuse it; otherwise open a new room. The peak number of rooms in use at any moment is the answer, which is a fundamentally different question from merge-overlapping-intervals: that problem asks for the union of overlapping ranges, while this one asks for the maximum number of ranges alive at the same instant, which can be larger than the number of merged groups whenever more than two meetings overlap at once.
Structured elaboration
Why this differs from merging overlapping intervals
Merging intervals collapses any chain of pairwise-overlapping intervals into one output range: three meetings that overlap in a chain (A overlaps B, B overlaps C, but A and C do not) merge into a single interval. Room counting instead asks how many of them are simultaneously alive, which is a different quantity: those same three meetings only ever need 2 rooms if A and C never overlap directly, even though they all merge into one interval. Room counting is a peak concurrency question, not a union of ranges question.
Why sorting starts and ends (or a heap of active ends) gets you there
Model each meeting as a +1 event at its start and a −1 event at its end. Sorting starts and ends and sweeping through events in time order lets you track the running concurrent count directly: the answer is the maximum value that running count ever reaches. A min-heap of active end times is an equivalent formulation of the same sweep: instead of a raw counter, the heap always tells you the earliest time a room becomes free, so you know immediately whether the next meeting can reuse an existing room or needs a new one.
Algorithm (steps)
- Sort meetings by start time.
- Maintain a min-heap of the end times of meetings currently occupying a room.
- For each meeting in start order: if the heap is non-empty and its minimum end time is ≤ this meeting's start, pop that end time (that room frees up) and push this meeting's end time in its place; otherwise push this meeting's end time as a new room.
- The final heap size is the minimum number of rooms needed.
Worked example
import heapq
def min_meeting_rooms(intervals: list[list[int]]) -> int:
"""
Minimum concurrent rooms needed. O(n log n) time, O(n) space (heap of end times).
"""
if not intervals:
return 0
ordered = sorted(intervals, key=lambda pair: pair[0])
heap: list[int] = [] # end times of meetings currently occupying a room
for start, end in ordered:
if heap and heap[0] <= start:
heapq.heapreplace(heap, end) # reuse the room that frees earliest
else:
heapq.heappush(heap, end) # need a new room
return len(heap)
if __name__ == "__main__":
sample = [[0, 30], [5, 10], [15, 20]]
print(min_meeting_rooms(sample))
no_overlap = [[7, 10], [2, 4]]
print(min_meeting_rooms(no_overlap))
Running this prints:
2
1
For [[0,30],[5,10],[15,20]]: room 1 opens for [0,30]; at start=5, the heap's minimum end is 30 which is not ≤ 5, so a new room opens for [5,10]; at start=15, the minimum end is now 10 (from the just-finished [5,10]), which is ≤ 15, so that room is reused for [15,20]; final heap size 2. For [[7,10],[2,4]] (sorted to [[2,4],[7,10]]): room 1 opens for [2,4]; at start=7, the minimum end 4 is ≤ 7, so the same room is reused; final heap size 1.
Complexity
Time: O(nlogn), dominated by the initial sort (heap operations are O(logn) each, over n meetings). Space: O(n) for the heap in the worst case, when every meeting overlaps every other.
Edge cases
- Empty input needs 0 rooms.
- A meeting that starts exactly when another ends is treated as not overlapping here (the room is reused): whether a meeting ending at t and one starting at t count as conflicting is a modeling choice to state up front.
- All meetings mutually overlapping (for example, everyone scheduled from 9am to 5pm) requires n rooms, the maximum possible.
- Duplicate identical meetings still each require their own room if they are genuinely simultaneous distinct bookings.
Trade-offs & pitfalls
The most common wrong turn is applying the merge-overlapping-intervals algorithm here and reporting the number of merged groups: that undercounts whenever three or more meetings overlap in a chain without all pairwise overlapping, since merging only tracks the union shape, not simultaneous occupancy. A second common gap is not being explicit about the boundary rule (does a meeting ending at t conflict with one starting at t), since interviewers frequently vary this to see if the candidate notices the assumption. For the streaming follow-up (meetings arriving one at a time rather than as a batch), the min-heap of active end times generalizes directly: insert the new end time, and if a room is reused, decrement the heap; there is no need to re-sort, since the heap already maintains order incrementally.
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.