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 static m x n matrix where every row and every column is individually sorted, and you must answer many 'does value x exist' queries against it as fast as possible. Walk through the preprocessing, space, and query-time trade-offs available (from no preprocessing at all up to full O(1) query time), and pick one given a stated memory budget.
Sample Answer
Direct answer
Because every row and every column is already sorted, a query needs no extra structure at all to run faster than a plain scan: starting the search from the top-right (or bottom-left) corner and stepping left or down as comparisons dictate finds any value in O(m+n) time with zero preprocessing and O(1) extra space. If memory allows more, the same mn values can be flattened and sorted once, trading O(mnlog(mn)) preprocessing and O(mn) space for O(log(mn)) binary-search queries, or hashed into a set once for O(mn) preprocessing time and space with O(1) average-case query time. Given a memory budget, the choice is really about how much of that one-time cost you can afford to pay before the first query ever arrives.
Structured elaboration
The full preprocessing/space/query spectrum
| Approach | Preprocessing time | Extra space | Query time |
|---|---|---|---|
| Corner (staircase) search | none | O(1) | O(m+n) |
| Sort all mn values once | O(mnlog(mn)) | O(mn) | O(log(mn)) |
| Hash all mn values once | O(mn) | O(mn) | O(1) average |
Why the corner search works with no preprocessing
Starting at the top-right corner, every step down increases the value (columns are sorted top to bottom) and every step left decreases it (rows are sorted left to right). Comparing the target against the current cell tells you unambiguously which single direction to move: if the cell is too large, the entire column below it is even larger, so move left; if too small, the entire row to its left is even smaller, so move down. Each comparison eliminates exactly one row or one column, giving at most m+n steps.
Why more preprocessing buys a faster query, and what it costs
Sorting or hashing all mn values loses the matrix's 2-D shape entirely, but that shape was only useful for the zero-preprocessing corner search; once every value is available as one flat sorted list or one flat hash set, the query becomes a standard 1-D lookup. The trade is a one-time O(mn) (hash) or O(mnlog(mn)) (sort) cost and O(mn) memory paid once, in exchange for every subsequent query dropping from linear-in-(m+n) to logarithmic or constant.
Picking one under a memory budget
- Budget is effectively O(1) (matrix itself is already large, or queries are rare): corner search, no preprocessing needed at all.
- Budget allows O(mn) but query-time determinism matters more than raw speed (e.g. needing a guaranteed worst-case bound rather than an average case): sort once, binary search each query, O(log(mn)) worst case, guaranteed.
- Budget allows O(mn) and queries dominate the workload (many queries, want the fastest possible average lookup, worst-case hash collisions are an acceptable risk): hash all values once, O(1) average query.
Worked example
Approach
Implement all three: the zero-preprocessing corner search, a sort-once-then-binary-search index, and a hash-once index, then confirm all three agree on the same matrix.
import bisect
def staircase_search(matrix, target):
# No preprocessing. O(m + n) time, O(1) extra space, per query.
if not matrix or not matrix[0]:
return False
m, n = len(matrix), len(matrix[0])
row, col = 0, n - 1
while row < m and col >= 0:
val = matrix[row][col]
if val == target:
return True
elif val > target:
col -= 1
else:
row += 1
return False
def build_sorted_index(matrix):
# Preprocessing: flatten and sort once. O(mn log(mn)) time, O(mn) space.
flat = [v for row in matrix for v in row]
flat.sort()
return flat
def query_sorted_index(sorted_flat, target):
# O(log(mn)) query time.
i = bisect.bisect_left(sorted_flat, target)
return i < len(sorted_flat) and sorted_flat[i] == target
def build_hash_index(matrix):
# Preprocessing: hash all values once. O(mn) time and space.
return {v for row in matrix for v in row}
def query_hash_index(value_set, target):
# O(1) average query time.
return target in value_set
matrix = [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30],
]
sorted_flat = build_sorted_index(matrix)
hash_index = build_hash_index(matrix)
for target in (5, 20, 30):
a = staircase_search(matrix, target)
b = query_sorted_index(sorted_flat, target)
c = query_hash_index(hash_index, target)
print(target, "-> staircase:", a, "sorted-index:", b, "hash-index:", c)
This prints:
5 -> staircase: True sorted-index: True hash-index: True
20 -> staircase: False sorted-index: False hash-index: False
30 -> staircase: True sorted-index: True hash-index: True
All three approaches agree on every target, confirming the corner-search logic and both preprocessed indexes reach the same answer; they only differ in when the work happens (per query, versus once up front) and how much memory they hold onto between queries.
Key points
- The corner search's step direction is decided in O(1) per cell, no lookahead or backtracking is needed, since the sorted-row/sorted-column structure guarantees the eliminated row or column can never contain the target.
- Sorting once amortizes its O(mnlog(mn)) cost over every future query; it only pays off once the number of queries is large enough that repeated O(m+n) corner searches would cost more in total.
- The hash-index's O(1) is an average-case guarantee (dependent on hash distribution), not a worst-case one; the sorted-index's O(log(mn)) is worst-case guaranteed.
Complexity
Staircase search: O(m+n) time per query, O(1) extra space, no preprocessing.
Sorted index: O(mnlog(mn)) one-time preprocessing, O(mn) space, O(log(mn)) time per query.
Hash index: O(mn) one-time preprocessing, O(mn) space, O(1) average time per query.
Edge cases
- Empty matrix, or a matrix with an empty first row: all three approaches should return
Falseimmediately without indexing errors, handled here by thenot matrix or not matrix[0]guard in the staircase search (the two indexed approaches naturally returnFalseon an empty structure). - Target smaller than every value, or larger than every value: the staircase search terminates in at most m+n steps by walking straight to a matrix edge without finding a match.
- Duplicate values scattered across the matrix: none of the three approaches are affected, since all only need existence, not counting or locating every occurrence.
Trade-offs & pitfalls
Building the sorted or hashed index and then never issuing enough queries to amortize its cost is a common miscalculation, if only a handful of queries will ever run against a given matrix, the corner search's zero preprocessing wins outright even though its per-query cost looks worse on paper. A second pitfall is assuming the hash-index's O(1) is a hard guarantee; adversarial inputs or unlucky hash collisions can degrade it, so a system with strict worst-case latency requirements should prefer the sorted-index's guaranteed O(log(mn)) instead. Finally, the corner search is not a general binary-search substitute, it exploits the fact that both rows and columns are sorted; if only one axis were sorted, a slower approach (binary search per row, O(mlogn)) would be needed instead.
Find the k-th largest element in an unsorted array. A full sort gets you there in O(n log n); explain how quickselect (partition-based, like quicksort but recursing into only one side) gets the expected time down to O(n), and when you would reach for a heap of size k instead.
Sample Answer
Direct answer
Quickselect adapts quicksort's partitioning to find just the k-th largest element without fully sorting: after one partition step around a pivot, the pivot's final position tells you whether the answer lies to its left or right, so you only ever recurse into one side instead of both. That halves (in expectation) the work at each level rather than branching into two recursive calls, which is what brings the expected time down from sorting's O(nlogn) to O(n). A heap of size k is the better choice instead when you cannot, or do not want to, mutate the input in place, or when the data arrives as a stream and you need the running top-k as you go rather than a single final answer.
Structured elaboration
Why quickselect is expected O(n)
A single partition around a random pivot costs O(n) and places the pivot at its correct sorted position, with everything smaller to its left and everything larger to its right. If that position is the one you are looking for, you are done; otherwise you recurse into only the one side that must contain the target index, discarding the other side's work entirely. With a reasonably balanced pivot (true on average for a random pivot), the total expected work follows the recurrence T(n)=T(2n)+O(n)=O(n) (expected), the same halving-geometric-series pattern that makes binary search O(logn), except here the per-level cost is O(n) rather than O(1), and only one recursive branch is taken rather than a binary search's implicit single branch. This is the key difference from quicksort, which must recurse into both sides to sort everything, giving O(nlogn).
Why a heap of size k instead
- Streaming input: if elements arrive one at a time and you must always be able to report the current top k, quickselect does not apply directly, since it needs the whole array in hand to partition; a size-k min-heap updates in O(logk) per new element and always reflects the current top k.
- Avoiding in-place mutation: quickselect partitions the input array in place; if the caller cannot have their array reordered, a heap that only reads elements avoids that side effect (at the cost of O(k) extra space).
- Worst-case guarantee: a naive quickselect has a worst case of O(n2) on an adversarial or unlucky pivot sequence (randomizing the pivot choice makes this astronomically unlikely, not impossible); a heap of size k guarantees O(nlogk) in every case.
- k close to n: when k is large relative to n, a heap of size k approaches O(k) extra space that is not much smaller than the array itself, and quickselect's in-place approach becomes the more memory-efficient option; when k is small, the heap's small extra space is a non-issue and its worst-case guarantee is attractive.
A related, absorbed framing: this is a selection-algorithm family, not a one-off trick
The same "avoid a full sort" idea generalizes. Finding the k-th smallest value in a matrix whose rows and columns are each sorted uses a min-heap over the smallest untried cell in each row (or a binary search directly over the value range, counting how many matrix entries are ≤ a candidate value in O(n) per probe) rather than flattening and sorting the whole matrix. And when memory, not just time, is the binding constraint (as in a memory-constrained k-smallest-elements variant), quickselect's in-place partitioning is preferable to a heap precisely because it needs no auxiliary structure beyond the input array itself.
Worked example
import heapq
import random
def kth_largest_quickselect(nums: list[int], k: int) -> int:
"""
Return the k-th largest value (k=1 is the maximum).
Expected O(n) time, O(1) extra space (in-place partition, iterative).
Worst case O(n^2) on adversarial pivots; randomized pivot makes that
astronomically unlikely rather than eliminating it.
"""
if not (1 <= k <= len(nums)):
raise ValueError("k out of range")
target = len(nums) - k # index of the k-th largest in sorted-ascending order
lo, hi = 0, len(nums) - 1
while True:
pivot_idx = random.randint(lo, hi)
nums[pivot_idx], nums[hi] = nums[hi], nums[pivot_idx]
pivot = nums[hi]
store = lo
for i in range(lo, hi):
if nums[i] < pivot:
nums[i], nums[store] = nums[store], nums[i]
store += 1
nums[store], nums[hi] = nums[hi], nums[store]
if store == target:
return nums[store]
elif store < target:
lo = store + 1
else:
hi = store - 1
def kth_largest_heap(nums: list[int], k: int) -> int:
"""Min-heap of size k. O(n log k) time, O(k) space."""
heap: list[int] = []
for x in nums:
if len(heap) < k:
heapq.heappush(heap, x)
elif x > heap[0]:
heapq.heapreplace(heap, x)
return heap[0]
if __name__ == "__main__":
random.seed(0)
data = [3, 2, 1, 5, 6, 4]
print("quickselect k=2:", kth_largest_quickselect(data.copy(), 2))
print("heap k=2:", kth_largest_heap(data, 2))
bigger = [7, 10, 4, 3, 20, 15]
print("quickselect k=3:", kth_largest_quickselect(bigger.copy(), 3))
print("heap k=3:", kth_largest_heap(bigger, 3))
Running this prints:
quickselect k=2: 5
heap k=2: 5
quickselect k=3: 10
heap k=3: 10
For [3, 2, 1, 5, 6, 4] sorted descending (6, 5, 4, 3, 2, 1), the 2nd largest is 5, and both methods agree. For [7, 10, 4, 3, 20, 15] sorted descending (20, 15, 10, 7, 4, 3), the 3rd largest is 10, and again both methods agree. The pivot choices inside quickselect are randomized but seeded (random.seed(0)), so this exact sequence of calls reproduces this exact output every time it is run.
Complexity
- Quickselect: expected time O(n), worst case O(n2); space O(1) extra (partitions in place, iteratively rather than recursively here).
- Heap of size k: time O(nlogk) in every case; space O(k) for the heap.
Edge cases
- k outside the range
[1, len(nums)]is invalid input and should raise rather than silently returning a wrong value. - Duplicate values are handled correctly by both methods, since partitioning and heap comparisons work on values, not identity.
- k equal to 1 (the maximum) or k equal to n (the minimum) are valid boundary cases worth checking by hand.
- An already-sorted or reverse-sorted array is exactly the input that most threatens a non-randomized quickselect's worst case; randomizing the pivot is what defends against it.
Trade-offs & pitfalls
The most common wrong turn is presenting quickselect as strictly superior because of its better expected time, without naming its O(n2) worst case or its requirement to mutate the input array in place; both are real costs that the heap approach avoids. A second common gap is forgetting that quickselect only gives you the k-th value itself, not the k values above it in order: if you also need the actual top-k list, you still need one more pass (or a heap) to collect everything on the correct side of the final partition. A third pitfall, specific to this absorbed question family, is treating "kth largest in an array" and "kth smallest in a sorted matrix" as needing the same algorithm: the matrix's extra structure (both rows and columns already sorted) is exactly what makes a heap-over-candidate-cells or binary-search-over-values approach effective there, and quickselect's partitioning does not directly apply to a two-dimensional sorted structure the same way.
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 an array containing only three distinct values, sort it in-place in a single pass using constant extra space (the Dutch National Flag problem). Then explain how the same three-way in-place partitioning idea generalizes to partitioning a list by an arbitrary predicate while keeping relative order stable.
Sample Answer
Direct answer
Sort the three-valued array in one pass with three pointers, low, mid, high, that carve it into a growing "already-placed-0s" region, a "confirmed-1s" region, and a "not-yet-placed-2s" region, swapping at most once per position and using no extra storage (the Dutch National Flag algorithm). The same low/high swap idea generalizes directly to a two-way in-place partition by any predicate, but that direct generalization is not stable: swapping elements out of place can scramble the relative order of items that land in the same output region, so keeping order stable needs an extra step beyond just relabeling the predicate.
Structured elaboration
The three-way invariant
At every point during the scan: everything before low is 0, everything in [low, mid) is 1, everything after high is 2, and mid is the next unclassified element. When nums[mid] == 0, swapping it to low and advancing both pointers is safe because the element that lands at mid from the swap was already known to be 1 (it came from inside [low, mid)). When nums[mid] == 2, swapping it to high and only decrementing high (not advancing mid) is required because the element swapped in from the unexplored tail is unclassified and must still be examined.
Generalizing to an arbitrary predicate, and where stability breaks
Collapsing the three categories to two, "satisfies the predicate" versus "does not", turns this into the standard in-place two-way partition: scan with a single pointer, swap anything satisfying the predicate to the front. This preserves the O(n) time, O(1) space profile, but it is not stable: a swap moves an element across positions that may already hold other same-category elements, and nothing about the swap preserves their relative order. The demonstration below shows two items in the same category (both satisfying the predicate) ending up reordered relative to each other purely because of how the swaps landed, even though the partition itself (which items are in which category) is correct.
To keep relative order stable while partitioning in place, the pointer-swap approach is not enough on its own. Two honest options:
- Trade space for stability (simple): scan once, appending predicate-true and predicate-false items to two separate output lists in encounter order, then concatenate. This is O(n) time and stable by construction, at the cost of O(n) auxiliary space, no longer in-place.
- Keep O(1) space, pay in time (advanced): a genuinely in-place and stable partition is possible using a recursive divide-and-rotate scheme, partition each half of the array independently, then merge the two halves' boundary regions by rotating the "false" suffix of the left half past the "true" prefix of the right half. This is the same technique behind library-grade in-place stable partitions (for example, C++'s
std::stable_partitionis specified to do at most O(nlogn) swaps in the general case, or a single linear pass if it is allowed to allocate a temporary buffer). It is a materially different algorithm from the plain DNF swap, not just the same three-pointer idea relabeled.
Worked example
Approach
First, the DNF sort itself:
def dutch_national_flag(nums):
low, mid, high = 0, 0, len(nums) - 1
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else: # nums[mid] == 2
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1
return nums
print(dutch_national_flag([2, 0, 2, 1, 1, 0]))
This prints [0, 0, 1, 1, 2, 2].
Second, the two-way generalization by predicate, showing the instability directly on tagged items so reordering is visible:
def unstable_partition(items, pred):
lo = 0
for i in range(len(items)):
if pred(items[i]):
items[lo], items[i] = items[i], items[lo]
lo += 1
return items
labeled = [('a', 1), ('b', 0), ('c', 1), ('d', 0), ('e', 1)]
print(unstable_partition(labeled[:], lambda t: t[1] == 1))
def stable_partition(items, pred):
true_bucket = [x for x in items if pred(x)]
false_bucket = [x for x in items if not pred(x)]
return true_bucket + false_bucket
print(stable_partition(labeled[:], lambda t: t[1] == 1))
This prints:
[('a', 1), ('c', 1), ('e', 1), ('d', 0), ('b', 0)]
[('a', 1), ('c', 1), ('e', 1), ('b', 0), ('d', 0)]
The swap-based version reorders 'b' and 'd' relative to each other (both are category-0, and 'd' ends up before 'b', the reverse of their original order), while the extra-buffer version preserves 'b' before 'd' exactly as encountered.
Key points
- The DNF three-pointer scan and the two-way predicate partition are the same swap mechanism; only the number of categories changes.
- Correctness of which bucket each item lands in is unaffected by the instability; only the order within a bucket is at risk.
- Stability and true in-place (O(1) space) are in tension for this problem: you can have both only by accepting O(nlogn) time via the rotation-based approach, or you can have O(n) time by giving up in-place-ness.
Complexity
DNF: time O(n) (single pass, mid never revisits a position), space O(1).
Unstable two-way partition: time O(n), space O(1).
Stable partition via extra buffer: time O(n), space O(n).
Edge cases
- Empty array, single element, or an already-sorted array: the DNF loop terminates immediately or after trivial no-op passes.
- All elements identical (all
1s, for instance):lownever advances,midsweeps straight tohighwith no swaps. - A predicate that is trivially true or false for every element: the two-way partition degenerates to a no-op copy.
Trade-offs & pitfalls
The most common mistake when moving from three-way DNF to a two-way predicate partition is assuming the result is automatically stable "because it's the same kind of algorithm." It is not, and that distinction matters directly whenever a partition needs to preserve, for example, insertion order or timestamp order within each output group (a very common real requirement, such as partitioning a task queue into "ready" versus "blocked" while keeping each group's original ordering). Reaching for the swap-based version there without checking the stability requirement is a silent correctness bug, not just a style choice. When stability genuinely is not required, the swap-based version remains the better default: no allocation, single pass, and it generalizes cleanly to k-way partitioning by widening from two pointers to k−1 boundary pointers.
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.
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.