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 string containing only the bracket characters ( ) { } [ ], determine whether it is validly nested: every closing bracket matches the most recently opened bracket of the same type. Solve it in O(n) time and explain what data structure makes 'most recently opened' cheap to query.
Sample Answer
Direct answer
Push every opening bracket onto a stack. On a closing bracket, it must match whatever opener currently sits on top of the stack; if it does not, or the stack is already empty, the string is invalid. After the scan, the string is valid only if the stack is empty, meaning every opener found a partner. This runs in O(n) time and O(n) space.
Structured elaboration
A stack models "the most recently opened, still-unclosed bracket" exactly, because it is last-in-first-out (LIFO): whichever opener was pushed most recently is always the one that must be closed next, and that is precisely what sits on top. Checking a closer against the top of the stack is an O(1) lookup through a small mapping () pairs with (, ] with [, } with {).
Counting bracket types separately (how many ( versus how many )) is not enough: a string can have perfectly equal counts of every bracket type and still be invalid because the nesting order is wrong, for example ([)]. Only a structure that remembers order, like a stack, can catch that.
Worked example
def is_valid_brackets(s: str) -> bool:
pairs = {")": "(", "]": "[", "}": "{"}
stack: list[str] = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack[-1] != pairs[ch]:
return False
stack.pop()
return not stack
if __name__ == "__main__":
tests = ["()[]{}", "(]", "([)]", "{[]}"]
print([is_valid_brackets(t) for t in tests])
Running this prints [True, False, False, True]. Trace ([)]: push (, push [, then see ); the top of the stack is [, which does not pair with ), so the function returns False immediately, even though the overall bracket counts are balanced.
Complexity
Time: O(n), one pass over the string doing O(1) work per character.
Space: O(n) worst case, since a string of all opening brackets pushes every character onto the stack before the scan ends.
Edge cases
- Empty string: the stack never receives a push, so it is empty at the end and the function correctly returns
True. - A lone unmatched opening bracket at the very end: the stack is non-empty when the scan finishes, so the final
not stackcheck (not just the per-character comparisons) is what catches it. - A closing bracket with nothing open:
stackis empty when a closer arrives, so the code must checknot stackbefore indexingstack[-1], or it raises instead of returningFalsecleanly.
Trade-offs & pitfalls
Using a single stack with a pairs mapping generalizes cleanly to any number of bracket types; writing a separate counter per bracket type cannot detect ordering violations no matter how many counters you add.
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.
For each element in an array, find the next element to its right that is strictly greater than it (or determine none exists), in O(n) time. Then explain how the same monotonic-stack idea lets you compute the largest rectangular area under a histogram in one pass.
Sample Answer
Direct answer
Scan left to right while keeping a stack of indices whose values are strictly decreasing from bottom to top; whenever the next value is bigger than the stack's top, that top index has found its next greater element, so pop it and record the match, repeating until the top is no longer smaller. The same "resolve everything the current value beats" idea, applied with the comparison direction flipped, is what lets the largest rectangular area under a histogram be computed in one pass instead of checking every pair of bars.
Structured elaboration
Approach: next greater element
- Keep a stack of indices; the invariant is that the values at those indices, read from bottom to top, are strictly decreasing.
- For each new value, while the stack is non-empty and the value at its top index is smaller than the current value, pop that index and record the current value as its next-greater element. Once the loop stops (top is
>=current, or the stack is empty), push the current index. - Every index is pushed exactly once and popped at most once, since once resolved it is never pushed again, so the total work across the
whileloop is bounded by n pushes plus n pops.
def next_greater_elements(nums):
"""
For each index i, find the value of the next element to the right that is
strictly greater than nums[i]. -1 if none exists.
"""
n = len(nums)
result = [-1] * n
stack = [] # indices whose next-greater is not yet resolved; values decreasing
for i, val in enumerate(nums):
while stack and nums[stack[-1]] < val:
idx = stack.pop()
result[idx] = val
stack.append(i)
return result
Approach: largest rectangle in histogram
- The same monotonic stack, kept in increasing order of height this time, finds each bar's nearest strictly-smaller bar on both the left and the right in a single left-to-right pass with a sentinel.
- When a new bar is shorter than the stack's top, the popped bar's rectangle is finalized: its height is the popped bar's height, and its width spans from the index just after the new stack top (its nearest-smaller-on-the-left) to the current index minus one (its nearest-smaller-on-the-right).
- Appending a sentinel value of 0 at the end forces every remaining bar on the stack to be closed out, so the loop doesn't need special-case cleanup after the main scan.
def largest_rectangle_area(heights):
"""
Largest rectangular area under a histogram, using a monotonic increasing
stack of indices (nearest-smaller-element on both sides).
"""
stack = [] # indices with strictly increasing heights
best = 0
extended = heights + [0] # sentinel forces every bar to be closed out
for i, h in enumerate(extended):
while stack and extended[stack[-1]] >= h:
height = extended[stack.pop()]
left_bound = stack[-1] if stack else -1
width = i - left_bound - 1
best = max(best, height * width)
stack.append(i)
return best
Key points
- Both problems rely on the same guarantee: once a stack entry is popped, its answer is final and never needs revisiting, which is what makes the total work linear instead of quadratic.
- Next-greater-element uses a decreasing stack (pop while top
<current); largest-rectangle uses an increasing stack (pop while top>=current), because it needs the nearest smaller value, not the nearest bigger one, on each side.
Worked example
next_greater_elements([2, 1, 2, 4, 3]) prints [4, 2, 4, -1, -1]. Tracing the stack (by index): push 0 (value 2). Index 1 (value 1) is not greater than 2, so push 1 (stack values by index: [2, 1]). Index 2 (value 2): pop index 1 since 1 < 2, so result[1] = 2; the new top is index 0 (value 2), and 2 is not < 2, so stop popping; push index 2. Index 3 (value 4): pop index 2 (2 < 4) giving result[2] = 4, then pop index 0 (2 < 4) giving result[0] = 4; push index 3. Index 4 (value 3): top is index 3 (value 4), not < 3, so just push. Final: result = [4, 2, 4, -1, -1].
largest_rectangle_area([2, 1, 5, 6, 2, 3]) prints 10: the bars of height 5 and 6 together span a width of 2, giving an area of 5 * 2 = 10, the largest rectangle available in this histogram.
Trade-offs & pitfalls
Complexity
next_greater_elements: Time O(n) amortized, since each index is pushed once and popped at most once. Space O(n) for the stack and result array in the worst case (a strictly increasing input pushes every index before any pop happens).
largest_rectangle_area: Time O(n), Space O(n) for the stack, by the same amortized argument.
Edge cases
- Next-greater: an empty array returns
[]; a strictly decreasing input means nothing is ever popped, so every result is-1; circular arrays (where the next greater element may wrap to the front) need iterating 2n times with modulo indices instead of just n. - Largest-rectangle: all-equal heights collapse to one big rectangle spanning the whole array; a single bar is its own rectangle; the trailing sentinel of 0 must be strictly smaller than every real height, which holds for any non-negative histogram.
Implementing next-greater with a nested loop that rescans from the current position for every element gives the same answer but degrades to O(n^2); the monotonic stack is what removes the rescanning. For the histogram problem, forgetting the sentinel means the last few bars left on the stack never get closed out and their rectangles are silently missed. This is the same monotonic-stack idea in both problems, and the Largest Rectangle in Histogram problem is the canonical harder application of it: instead of asking "what's the next bigger value," it asks "how far can this bar's height extend before hitting something shorter on each side," the nearest-smaller-element query in both directions at once.
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.
Here is a binary search that computes mid as (low + high) / 2. What can go wrong with this specific expression on very large arrays or in languages with fixed-width integers, and how would you rewrite it to avoid the problem?
Sample Answer
Direct answer
Computing mid as (low + high) / 2 can overflow the integer type's range when low and high are both large, since their sum may exceed what a fixed-width integer can represent; in a language like C++ this is undefined behavior for signed types, not just a wrong answer. The fix computes the same midpoint using only a difference, mid = low + (high - low) / 2, so the intermediate value never exceeds the larger of the two bounds.
Structured elaboration
Approach
- The failure mode: if
lowandhighare both close to a signed integer type's maximum representable value, their sum overflows before the division ever happens. For signed integers, the C++ standard says this overflow is undefined behavior (UB), meaning the compiler is free to produce any result, not just a predictable wraparound. - The fix reframes the formula around the gap between the bounds instead of their sum:
low + (high - low) / 2. Sincehigh - lowis bounded byhighitself (wheneverlow >= 0), this expression never produces an intermediate value larger thanhigh, so it cannot overflow ifhighis representable. - A modern alternative in C++20 is
std::midpointfrom<numeric>, a standard library function written specifically to compute the midpoint of two values without ever overflowing, regardless of the formula it uses internally.
#include <cstdio>
#include <climits>
int mid_unsafe(int low, int high) {
return (low + high) / 2; // low + high can exceed INT_MAX
}
int mid_safe(int low, int high) {
return low + (high - low) / 2; // high - low never exceeds the larger bound
}
int main() {
int low = INT_MAX - 4;
int high = INT_MAX;
printf("low=%d high=%d\n", low, high);
printf("unsafe mid (undefined behavior, likely wraps negative): %d\n", mid_unsafe(low, high));
printf("safe mid: %d\n", mid_safe(low, high));
return 0;
}
Key points
- The bug only shows up near the type's upper bound, so it can pass ordinary small-input tests and still fail in production on large arrays, or on other languages where indices or values sit close to the type's maximum.
- Signed overflow is undefined behavior in C++, so the visible symptom (wrapping to a negative number) isn't even guaranteed, though it's the common observed behavior; unsigned overflow, by contrast, is well-defined modular wraparound.
Worked example
low = INT_MAX - 4, high = INT_MAX (adjacent to the top of a 32-bit signed range). Compiled with -fwrapv (a compiler flag that makes signed overflow wrap deterministically, used here only so the demonstration is reproducible rather than relying on undefined behavior), this program prints:
low=2147483643 high=2147483647
unsafe mid (undefined behavior, likely wraps negative): -3
safe mid: 2147483645
The unsafe formula's sum, 2147483643 + 2147483647 = 4294967290, exceeds the 32-bit signed maximum of 2147483647, wraps around under -fwrapv, and divides to a nonsensical negative midpoint. The safe formula computes high - low = 4, halves it to 2, and adds it to low to get 2147483645, which sits correctly between low and high.
Trade-offs & pitfalls
Complexity
Both formulas are O(1) time and O(1) space; the fix changes correctness, not complexity.
Edge cases
low > high(an empty search range):high - lowis negative, and signed division still works, but confirm your invariant never calls this on an invalid range.- Half-open versus inclusive interval conventions (
[low, high)versus[low, high]): the boundary update after comparingmid(low = mid + 1versushigh = mid, orhigh = mid - 1) must match whichever convention was chosen, or the loop can either run forever or skip the correct answer. - Unsigned index types (such as
size_t):high - lowis safe as long ashigh >= low, but ifhighcan ever be less thanlow, unsigned subtraction wraps to a huge positive number instead of going negative, a silent bug in the opposite direction.
This class of bug is a general lesson, not specific to binary search: any time two potentially large bounded values are summed before dividing (midpoints, averages, index arithmetic), it's worth asking whether the sum itself can exceed the type's range, and preferring difference-based formulas or a wider intermediate type (promoting to a 64-bit type before the addition) when it can.
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.