Skip to content
Tech Interview Prep
Technical interview guide

Sliding Window

A variable- or fixed-size window over a sequence, expanded and contracted in O(n) total instead of recomputing from scratch.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: Language-neutral, with container costs cited from CPython 3.14 and the C++ standard containers.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain the sliding-window idea and how it changes a production decision.

Answer

The 90-second version. A sliding window keeps a summary of one contiguous range and moves its two boundaries one step at a time, updating the summary incrementally instead of rebuilding it. The production decision it changes is whether you can afford to evaluate a rule per request inline: incremental update makes each boundary move O(1), so a per-request check costs the same whether the window holds 10 events or 10,000. That is the difference between a rate limiter that runs at the edge and one that has to be precomputed in batches.

Mechanism. Extending right adds one element's contribution; shrinking left removes one. Both are O(1) if the summary supports add and remove.

Python
# O(1) per boundary move
total += a[right]
total -= a[left]

# Same shape, quadratic cost: rebuilds the window on every move
total = sum(a[left:right + 1])

At n = 100,000 with a window of 1,000, the first is 100,000 operations; the second is ~100 million. (Worked example.)

Where it decides a production choice. Rate limiting is the case interviewers reach for, and the alternatives differ on memory and boundary accuracy:

ApproachPer-key stateBoundary behaviourReach for it when
Fixed window counter2 intsallows up to 2× the limit across the boundaryabuse protection, memory-tight
Sliding window counter2 ints + window startblends the current window with the fraction of the previous one still inside the range; worst-case error is one previous window's worth of requestsdefault for most public APIs
Sliding window logone timestamp per requestexactbilling, contractual limits

Worked figures: a 100 req/min limit with 1M active keys. The log stores up to 100 timestamps × 8 bytes ≈ 800 B/key → ~800 MB. The counter stores ~16 B/key → ~16 MB. That 50× gap is the deciding criterion when the limit is advisory; when it is contractual, you pay the memory for exactness.

When not to use it. A sliding window needs a summary that supports removal. Sums, counts and rates do. Max and min do not: removing the maximum requires knowing the next-largest, so you keep a monotonic deque instead. Trace for window size 3 over [1, 3, -1, -3, 5, 3, 6, 7]:

ivaluedeque (indices) after pushwindow max
01[0]–
13[1]–
2-1[1, 2]3
3-3[1, 2, 3]3
45[4]5
53[4, 5]5
66[6]6
77[7]7

Maxima: 3, 3, 5, 5, 6, 7. The deque gives O(1) amortised max, but it only supports removal from the ends: you cannot evict an arbitrary element, so it does not generalise to a window whose boundaries move out of order. Prefix sums are the other alternative: O(n) precompute, O(1) for any range query, but they need the whole array resident and an invertible summary, so they do not work on a stream.

Failure modes. Recomputing the summary inside the loop restores the quadratic cost while the code still looks like a sliding window; small inputs and short windows hide it. Detect it by counting operations per element or profiling, if per-element cost grows with window size, the summary is being rebuilt. In the deque version, forgetting to evict the front index when it falls out of the window returns a stale maximum; assert the front index is always ≥ right − k + 1.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How would you reason about fixed-size windows in a system you own?

Answer

Core answer (first 90 seconds)

A fixed-size window is a tumbling window: time is cut into non-overlapping buckets of width W, and an event's bucket is floor(ts / W). Every event lands in exactly one bucket, so per key you keep one counter and one bucket id. That is the whole appeal: O(1) state, O(1) update, trivially shardable, and the counter is a single integer you can INCR in Redis.

I reach for it when the question is "how many in this minute" and I can tolerate the two structural defects it has. I reach for something else when I can't.

Assumptions I'd state up front: W is fixed and known; events carry a timestamp I trust; I care about per-key counts, not exact ordering.

The two defects

Boundary burst. Because buckets don't overlap, a client can spend its full budget at the end of one bucket and again at the start of the next. With a 100 req/min limit, 100 requests at 00:59.9 and 100 at 01:00.1 is 200 requests in 200 ms, 2x the limit, and the limiter never fires. Detection: log the max count over any rolling 60 s window and compare it to the fixed-window count; the ratio is your burst factor, bounded by 2x for a single boundary.

Metric aliasing. A 30 s spike straddling the seam is split across two buckets, so each reports half the peak. Your 60 s max looks like 50% of the real burst. Detection: keep a 1 s-resolution series alongside and compare its max to the 60 s bucket max; a persistent ~2x gap means spikes are landing on boundaries.

Alternatives and when to use them

SchemeState per keyBurst at boundaryUse when
Tumbling (fixed)1 counter + bucket idup to 2xcoarse quotas, cheap metrics
Sliding logtimestamp per eventnoneexact limits, low volume
Sliding counter (ring of W/step buckets)W/step counters~1 + step/Wsmooth limits, bounded memory
Token buckettokens + last refill tsup to bucket capacitybursts are a feature

A sliding counter with step = W/10 cuts the boundary burst to ~1.1x for 10x the state. Token bucket is right when bursts are deliberate: it's what most API gateways ship.

Python
W, STEP = 60, 6
N = W // STEP                      # 10 slots
ring = [0] * N
last_step = -1

def add(ts, n=1):
    global last_step
    step = ts // STEP
    if step != last_step:          # entering a new step: clear the slot we reuse
        ring[step % N] = 0
        last_step = step
    ring[step % N] += n

def count(ts):
    return sum(ring)               # last W seconds, accurate to +/-STEP

Failure modes in a system you own

  • Clock skew. If N nodes each compute floor(ts/W) from their own clock, a 50 ms skew puts events near the seam in different buckets: double-counting or gaps. Fix: bucket on event time and let one aggregator assign buckets, or use a logical clock.
  • Event time vs processing time. Bucketing on arrival time means a 5-minute consumer lag shifts every event into the wrong bucket. Bucket on event time with a watermark, and decide explicitly whether late events are dropped or re-emit a correction.
  • Hot key. One counter per key means one Redis key; a hot tenant can push a single shard past ~100k ops/s. Shard the counter and sum on read.
  • Late data. A watermark that's too tight drops events silently; too loose and windows never close. Track the late-drop rate as a metric.

What I'd actually do

Start with tumbling windows plus a 1 s-resolution series for detection. If the burst factor or the aliasing gap matters, move to a sliding counter. Write down which defect you're accepting: "we use fixed windows" without that sentence is how the 2x burst ships.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through variable-size windows, including where engineers most often get it wrong.

Answer

The core, in the first minute. Variable-size windows apply when the window is defined by a predicate on its contents rather than a fixed length. Two pointers start at 0. right advances every iteration; left advances only while the window violates the predicate. The invariant after the shrink loop: [left, right] is valid, and left is the smallest index for which it is. Because left never moves backward, it advances at most n times over the whole run: the inner while is amortised O(1) per step, so the scan is O(n), not O(n²). State that invariant before writing code; it is what the interviewer is checking.

Worked trace. Longest substring without repeating characters, s = "abba":

Python
def longest_unique(s):
    seen = set()
    left = best = 0
    for right, ch in enumerate(s):
        while ch in seen:          # shrink until ch is admissible
            seen.remove(s[left])
            left += 1
        seen.add(ch)
        best = max(best, right - left + 1)
    return best
rightchshrinkleftwindowbest
0a—0"a"1
1b—0"ab"2
2bremove a, remove b2"b"2
3a—2"ba"2

Returns 2. left moved twice across four iterations: that is the amortisation, visible.

Where engineers get it wrong.

  1. if instead of while. Same input, if ch in seen: seen.remove(s[left]); left += 1: at right=2 it removes only a, leaving seen={b}, then re-adds b and records window "bb" as length 2; at right=3 it adds a and records "bba" (indices 1–3) as length 3. The answer is 3, and the reported window contains a repeat. The if version's window length is non-decreasing and can grow while the window is invalid.

  2. Calling it O(n²) because the inner loop looks nested. Count left's total movement, not its movement per iteration.

  3. Applying it when the predicate is not monotonic. "Subarray sum equals k" with negatives: shrinking can move the sum toward or away from k, so "left is the smallest valid index" fails and the scan misses answers. Use prefix sums in a hash map.

Alternatives, and when the pattern does not apply.

  • Jump-the-left: when the violation pins left to a computable index, skip the loop. For distinct characters, left = max(left, last[ch] + 1). Same O(n), no shrink loop; only valid when the new left is a direct function of the offending element.
  • Monotonic deque: when the predicate depends on an extremum ("longest window with max − min ≤ k", "max of every window of size k"), a running sum cannot evict the departing element's contribution. Keep indices in a deque with monotonic values; O(n) amortised.
  • Prefix sums + hash map: when the predicate is not monotonic in window length, or when you need counts of windows rather than the longest.

Failure modes to name. if for while; recording best before shrinking; forgetting to undo the aggregate when left moves (seen.remove(s[left]), total -= a[left]); length off by one (right - left + 1); and claiming O(n) without checking that the predicate is monotonic in window length.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

How do you implement the variable-size sliding window pattern to find the Longest Substring Without Repeating Characters in O(N) time?

Answer

Clarify first, then answer. "Substring" means contiguous, and we return the length, not the substring. The alphabet is whatever the input type gives us: for a Python str that's Unicode code points, for bytes it's 0–255. With that fixed, the answer is one pass with a hash map from character to its last index and a left pointer that jumps instead of creeping. O(N) time, O(min(N, |Σ|)) space.

The generic variable-size window, and how this problem maps onto it

Python
left = 0
for right in range(n):
    # expand: incorporate s[right]
    while window_invalid():
        # shrink: remove s[left]; left += 1
    update_answer()

Here the shrink loop collapses to a single assignment. The window can only become invalid for one reason, s[right] duplicates a character already inside it, and the fix is to move left past that character's previous occurrence in one step. That is the variable-size part: the window grows by 1 per iteration and shrinks by an arbitrary amount, but each index enters and leaves the window at most once, so total work is O(N).

Python
def length_of_longest_substring(s: str) -> int:
    last_seen: dict[str, int] = {}
    left = 0
    max_len = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1
        last_seen[ch] = right
        max_len = max(max_len, right - left + 1)
    return max_len

Worked trace: s = "abba"

This input is the one that separates a correct implementation from a plausible-looking one.

Steprightchlast_seen before stepAction on leftWindowmax_len
10'a'{}not seen → left = 0"a" [0:0]1
21'b'{'a': 0}not seen → left = 0"ab" [0:1]2
32'b'{'a': 0, 'b': 1}1 >= left (0) → left = 2"b" [2:2]2
43'a'{'a': 0, 'b': 2}0 < left (2) → ignore, left = 2"ba" [2:3]2

At step 4 the stored index for 'a' is stale: it sits behind left. Without the last_seen[ch] >= left guard, left would regress from 2 to 1, re-admitting the 'b' at index 1 and reporting an invalid window of length 3. The guard (equivalently, left = max(left, last_seen.get(ch, -1) + 1)) is what keeps left monotonic.

Complexity and memory trade-offs

  • Time: O(N). right visits each index exactly once and left only ever moves forward, so there are no inner shrinking steps. Python dict lookup and insertion are O(1) amortised.
  • Space: O(min(N, |Σ|)). For ASCII or Latin-1, |Σ| ≤ 256, so the map is bounded by a constant. In C++ where allocation matters, replace the hash table with a flat array and drop the hashing entirely:
C++
std::array<int, 256> last; last.fill(-1);
int left = 0, max_len = 0;
for (int right = 0; right < (int)s.size(); ++right) {
    unsigned char c = s[right];
    left = std::max(left, last[c] + 1);
    last[c] = right;
    max_len = std::max(max_len, right - left + 1);
}

Failure modes an interviewer will probe

  • Updating max_len only after the loop. The longest window often ends before the last index: "pwwkew" returns 3 ("wke"), while the final window is "ew", length 2. Update inside the loop.
  • Unicode. Iterating UTF-8 bytes splits multi-byte code points, so a byte-level answer is wrong for non-ASCII input. Decode to code points first (Python str already does), or state that the unit is bytes.
  • Returning the substring. Track best_start whenever max_len improves, then return s[best_start:best_start + max_len].
  • Empty input falls out correctly: the loop body never runs and 0 is returned.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How do you determine the total number of subarrays satisfying a condition using a sliding window?

Answer

To count the total number of subarrays satisfying a monotonic condition (such as subarray product strictly less than $k$ on positive integers, or subarray sum at most $S$), maintain a valid variable-size window [left, right]. For each step where you advance right, contract left until the window condition holds. The number of valid subarrays that end specifically at index right is exactly right - left + 1.

Mechanism

A contiguous subarray is uniquely identified by its pair of indices (i, right). If the property is monotone, meaning any subsegment of a valid window is also valid, then whenever the window [left, right] is valid, every subarray starting at index i (where left <= i <= right) and ending at right is also valid. Because there are right - left + 1 choices for i, adding this span at each step counts every valid subarray exactly once.

Python
def num_subarray_product_less_than_k(nums: list[int], k: int) -> int:
    if k <= 1:
        return 0  # Assuming elements are positive integers >= 1

    prod = 1
    left = 0
    total_count = 0

    for right, val in enumerate(nums):
        prod *= val
        while prod >= k and left <= right:
            prod //= nums[left]
            left += 1
        total_count += right - left + 1

    return total_count

Worked Trace

Consider nums = [10, 5, 2, 6] and k = 100:

rightvalprod before shrinkleft adjustmentValid windowValid subarrays ending at rightContribution (right - left + 1)Running total_count
01010left = 0[10][10]$0 - 0 + 1 = 1$1
1550left = 0[10, 5][5], [10, 5]$1 - 0 + 1 = 2$3
22100$100 \ge 100 \implies$ drop 10, left = 1, prod = 10[5, 2][2], [5, 2]$2 - 1 + 1 = 2$5
3660left = 1[5, 2, 6][6], [2, 6], [5, 2, 6]$3 - 1 + 1 = 3$8

Total count is 8.

Complexity and Failure Modes

  • Complexity: $O(N)$ time and $O(1)$ auxiliary space. Even though there is an inner while loop, left increments at most $N$ times across the entire iteration, yielding an amortized constant number of operations per element.
  • Violation of Monotonicity: This counting logic breaks if elements can be zero or negative. With negative numbers, expanding a window can cause a condition to toggle from false to true and back, destroying the guarantee that all subsegments ending at right are valid. In those non-monotone cases, sliding window fails and prefix sums paired with hash maps (or balanced trees) are required.
  • Exact vs. At-Most: If the problem asks for an exact count (e.g., "count of nice subarrays" with exactly $k$ odd numbers), the condition is not monotone with respect to inclusion. You solve it by decomposing: count(exact k) = count(at most k) - count(at most k - 1).

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

How do you solve subarray counting problems with exact constraints, like exactly K distinct values, using sliding windows?

Answer

An exact constraint like "contains exactly $K$ distinct elements" breaks standard two-pointer monotonicity: expanding the right edge can turn an invalid window valid, but expanding further can keep it valid before eventually breaking it, while shrinking the left edge does not yield a monotonic boundary for counting.

To restore monotonicity, decompose the exact count into two monotonic predicates: $$\text{count}(\text{exactly } K) = \text{count}(\text{at most } K) - \text{count}(\text{at most } K - 1)$$

Why Monotonicity Holds for "At Most $K$"

If a contiguous subarray nums[left..right] contains at most $K$ distinct elements, every subarray ending at right and starting at or after left (nums[i..right] for all $i \in [\text{left}, \text{right}]$) also contains at most $K$ distinct elements. As right moves forward from $0$ to $n-1$, left only moves forward to restore the condition len(freq) <= K. At each step $right$, the number of valid subarrays ending at right is exactly right - left + 1.

Implementation Trace

Python
from collections import defaultdict

def subarrays_with_k_distinct(nums: list[int], k: int) -> int:
    def at_most(limit: int) -> int:
        if limit <= 0:
            return 0
        freq = defaultdict(int)
        left = 0
        count = 0
        for right, val in enumerate(nums):
            freq[val] += 1
            while len(freq) > limit:
                out = nums[left]
                freq[out] -= 1
                if freq[out] == 0:
                    del freq[out]
                left += 1
            count += right - left + 1
        return count

    return at_most(k) - at_most(k - 1)

Consider nums = [1, 2, 1, 2, 3] with $K = 2$:

Index (right)Elementat_most(2) valid leftWindowSubarrays ending at right (right - left + 1)Cumulative at_most(2)at_most(1) ending at rightCumulative at_most(1)
010[1]1111
120[1, 2]2312
210[1, 2, 1]3613
320[1, 2, 1, 2]41014
433[2, 3]21215

Result: at_most(2) - at_most(1) = 12 - 5 = 7.

Complexity and Failure Modes

  • Time Complexity: $O(N)$ operations. Both right and left advance at most $N$ times across each of the two passes, with $O(1)$ amortised hash-map operations.
  • Space Complexity: $O(K)$ auxiliary space to track window frequencies.
  • The $K=0$ boundary edge case: Invoking at_most(0) without guarding limit <= 0 can lead to an infinite shrink loop or negative counts. Returning 0 immediately when limit <= 0 prevents map corruption.
  • Hash map removal omission: Failing to del freq[out] when count drops to zero keeps stale keys in the map, causing len(freq) to overreport distinct counts.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

How do you solve Minimum Window Substring using a sliding window and frequency map, and how do you track valid match counts efficiently?

Answer

To solve Minimum Window Substring in strictly $O(|S| + |T|)$ time and $O(|\Sigma|)$ auxiliary space, we use a two-pointer sliding window coupled with an aggregate match counter rather than comparing map snapshots on every step.

Mechanism

Let $T$ define target character demands and $S$ be the source string. We maintain two frequency maps (or fixed-size integer arrays if the alphabet is bounded, such as ASCII 128 or 256):

  1. target: Required frequency per character.
  2. window: Current counts inside the window $[left, right)$.

Comparing two maps naively costs $O(|\Sigma|)$ per window adjustment, degrading overall runtime to $O(|\Sigma| \cdot |S|)$. Instead, maintain two scalar counters:

  • required: Total number of distinct characters in $T$ with non-zero demand (len(target)).
  • formed: Number of distinct characters whose frequency inside the window meets or exceeds their target requirement (window[c] >= target[c]).
S = "ADOBECODEBANC", T = "ABC"
target = {'A': 1, 'B': 1, 'C': 1}, required = 3

Expand right until formed == required:
[A D O B E C] O D E B A N C   -> Window contains A:1, B:1, C:1 (formed = 3, valid)
Contract left to minimise:
 A [D O B E C] O D E B A N C  -> Dropping 'A' makes window[A]=0 < target[A], formed drops to 2 (invalid)

Python Implementation

Python
from collections import Counter

def min_window(s: str, t: str) -> str:
    if not s or not t:
        return ""

    target = Counter(t)
    required = len(target)

    window = {}
    formed = 0
    left = 0

    # Best window tracking: (window_length, start_index, end_index)
    best = (float("inf"), 0, 0)

    for right, char in enumerate(s):
        window[char] = window.get(char, 0) + 1

        # Increment formed only when frequency matches target exactly
        if char in target and window[char] == target[char]:
            formed += 1

        # Contract window from the left while validity holds
        while left <= right and formed == required:
            cur_len = right - left + 1
            if cur_len < best[0]:
                best = (cur_len, left, right)

            left_char = s[left]
            window[left_char] -= 1
            if left_char in target and window[left_char] < target[left_char]:
                formed -= 1

            left += 1

    return "" if best[0] == float("inf") else s[best[1]:best[2] + 1]

Complexity & Amortisation

  • Time Complexity: $O(|S| + |T|)$. Constructing target takes $O(|T|)$. Both left and right advance monotonically from $0$ to $|S|$, meaning each character enters the window once and leaves at most once. Character map updates and scalar comparisons are $O(1)$.
  • Space Complexity: $O(|\Sigma|)$ where $\Sigma$ is the alphabet size (at most $O(\min(|S|, |T|, |\Sigma|))$ entries in the hash maps).

Common Failure Modes

  1. Incrementing formed past 1 per character: Triggering if window[char] >= target[char]: formed += 1 on repeated additions inflates formed whenever an already-satisfied character is encountered. Check exact equality window[char] == target[char] during expansion, and strictly less window[char] < target[char] immediately after decrementing during contraction.
  2. Filtering optimization trade-offs: For sparse targets where $|S| \gg |T|$, creating a filtered list of (index, char) pairs for characters present in $T$ avoids stepping over irrelevant noise in $S$, reducing the sliding loop iterations from $|S|$ to the number of target occurrences in $S$.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

When does a sliding window have to carry the contents of the window rather than just its length, and how do you update that state as the window advances: say, for longest repeating character replacement?

Answer

The discriminator. A window can be a pair of indices only when validity is a function of width. That holds when the constraint is monotone in window size and summarisable as one scalar: a sum of non-negative values, an element count, a max held in a monotonic deque. The moment the constraint is about the multiset (distinctness, a per-character frequency cap, multiset equality) the window has to carry a frequency map, and usually a scalar summary of that map so validity stays O(1) instead of O(alphabet).

Longest repeating character replacement is the clean case. A window is valid iff len - max_freq <= k, where max_freq is the highest count of any single character inside it. State: counts, max_freq, left.

python

Python 3.14

def character_replacement(s: str, k: int) -> int: counts = {} left = max_freq = best = 0 for right, ch in enumerate(s): counts[ch] = counts.get(ch, 0) + 1 # add on the right max_freq = max(max_freq, counts[ch]) if (right - left + 1) - max_freq > k: # invalid: shrink once counts[s[left]] -= 1 # remove on the left left += 1 best = max(best, right - left + 1) # read the answer off the width return best

What is added, what is removed, what is read. Right pointer: increment counts[ch], then raise max_freq if this character just became the most frequent. Left pointer: decrement counts[s[left]] and advance, but max_freq is not recomputed. The answer is never read off the map; it is read off the window width, right - left + 1, maximised across the scan.

Trace s = "AABABBA", k = 1:

rightchcounts after addmax_freqwindowlen - max_freqbest
0AA:11[0,0]01
1AA:22[0,1]02
2BA:2 B:12[0,2]13
3AA:3 B:13[0,3]14
4BA:3 B:23[1,4]14
5BA:2 B:33[2,5]14
6AA:2 B:23[3,6]14

Row 6 is the interesting one: the window "ABBA" is not actually valid. Its true max frequency is 2, so it needs two replacements. The stale max_freq of 3 makes the test too permissive. The answer is still 4 because "AABA" (rows 0–3) is genuinely valid.

Why not decrement max_freq. It is an upper bound on the current window's true max frequency and a lower bound on the best any window has seen. Window length is non-decreasing, each step adds one on the right and removes at most one on the left, and every length the test accepts is realised by a real window: take the window in which max_freq was attained and extend it rightward to the current length; it still holds max_freq copies of that character, so it satisfies the constraint. Recomputing the true max on every shrink is also correct, but costs O(alphabet) per step: a constant over 26 letters, not a constant over a general alphabet.

When length alone is enough.

ConstraintState carriedWhy
sum of non-negative values <= Srunning summonotone in width
at most K distinctfreq map + distinct counterneed to know when a count hits 0
anagram / permutation matchfreq map + matches countermultiset equality, not width
replacement budgetfreq map + max_freq boundvalidity is width minus max_freq

Failure modes. The distinct counter breaks if a key is left in the map at count 0, because len(counts) then overcounts. Recomputing len(set(s[left:right+1])) per step is O(n·k). In fixed-width windows such as anagram search, removing the outgoing character before adding the incoming one is the usual off-by-one. All three are caught by a brute-force O(n²) oracle on random strings of length <= 12 with a fixed seed, which is cheaper to write than a hand trace and finds the stale-state bugs hand traces miss.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How would you explain the deque as the underlying container without using the usual slogan?

Answer

The 90-second version

The slogan is "O(1) at both ends". The mechanism behind it: a deque is not one contiguous buffer. CPython's collections.deque is a doubly-linked list of fixed-size blocks, 64 pointers each, plus a head and tail index into the two end blocks. Appending or popping at either end writes one slot and moves one index; nothing else in the structure moves. A list is a single contiguous allocation, so pop(0) has to memmove the remaining n-1 pointers down by one slot.

That difference is measurable without a stopwatch. Count the pointer moves:

Python
n = 5
lst = list(range(n))
moves = 0
while lst:
    lst.pop(0)        # shifts the remaining len(lst) elements left
    moves += len(lst)
print(moves)          # 4+3+2+1+0 = 10

For n elements that is n(n-1)/2 moves: 10 at n=5, ~5×10⁹ at n=100,000. A deque drains the same input in n operations. That is the difference between linear and quadratic, and it is a property of the layout, not of the machine.

What it costs you

The block layout is not free. CPython documents indexed access as O(1) at the ends but O(n) in the middle, because dq[i] walks the block chain. So a deque is not a drop-in for a list: if the algorithm indexes into the middle of the window, you have traded a quadratic removal for a linear lookup.

Alternatives, and when each wins

StructureBoth endsIndex iBounded memoryNotes
list + head indexO(1) amortisedO(1)no: grows unless compactednever actually remove; advance an index. Best when the window is a prefix of a stream you can reset.
ring buffer (fixed array + head/tail)O(1)O(1)yeswhat you write when latency and memory must be predictable; cache-friendly.
collections.dequeO(1)O(n) middlewith maxlenappend/popleft are atomic under the GIL; maxlen gives you a bounded ring for free.
Rust VecDequeO(1)O(1)growsring buffer over a growable allocation.
Java ArrayDequeO(1)O(1)growscircular array; the default choice over LinkedList.

Deciding criteria, in order: does the algorithm need random access into the window (then a ring buffer or VecDeque, not a deque)? Is memory bounded (then maxlen or a fixed ring)? Is it shared across threads (then deque's atomic ends, or an explicit lock)?

Failure modes

  • list.pop(0) inside a loop: quadratic, and the code looks correct. Detect it by scaling, double n and the runtime quadruples, or by profiling, where pop dominates.
  • Indexing a deque in the middle of a hot loop: O(n) per access. The same scaling test catches it.
  • An unbounded deque used as a queue: memory grows with the producer. maxlen or an explicit drain bounds it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How do you use a sliding window combined with a monotonic deque to solve the Sliding Window Maximum problem in O(N) time?

Answer

The 90-second answer. Keep a deque of indices whose values are strictly decreasing front to back. The front is always the current window's maximum. For each new index right: pop from the back while the back's value is <= nums[right]. Those elements can never be a maximum again, because right is newer and at least as large. Push right, pop the front if it has fallen out of the window (q[0] <= right - k), then emit nums[q[0]] once right >= k - 1. Every index enters and leaves the deque at most once, so the whole pass is O(n) time and O(k) space. Assumptions: 1 <= k <= n; if k > n there is no window and the function returns [].

Invariant and Mechanism

The deque holds two invariants at every step:

  1. Index validity: every stored index i satisfies right - k + 1 <= i <= right.
  2. Monotonicity: for indices stored front to back, i1 < i2 implies nums[i1] > nums[i2].

Because the values are strictly decreasing, deque[0] is the window maximum. The purge is what makes it amortised O(1): an element popped from the back is gone permanently, and each index is pushed once and popped at most once.

Python Implementation

Python
from collections import deque

def max_sliding_window(nums: list[int], k: int) -> list[int]:
    if not nums or k <= 0:
        return []
    if k == 1:
        return list(nums)

    q = deque()  # stores indices
    out = []

    for right, val in enumerate(nums):
        # 1. Maintain monotonic decreasing order
        while q and nums[q[-1]] <= val:
            q.pop()
        q.append(right)

        # 2. Drop index falling behind left window edge (right - k + 1)
        if q[0] <= right - k:
            q.popleft()

        # 3. Collect window maximum once first window is saturated
        if right >= k - 1:
            out.append(nums[q[0]])

    return out

Trace Example

For nums = [1, 3, -1, -3, 5], k = 3:

Step (right, val)Tail PopDeque (indices)Deque (values)Head EvictedWindow Max (right >= 2)
0 (1)None[0][1]No—
1 (3)Pop 0 (1 <= 3)[1][3]No—
2 (-1)None[1, 2][3, -1]No3 (nums[1])
3 (-3)None[1, 2, 3][3, -1, -3]No3 (nums[1])
4 (5)Pop 3, 2, 1 (<= 5)[4][5]No (q[0]=4 > 1)5 (nums[4])

Output: [3, 3, 5].

Failure Modes

Wrong eviction bound. The window is [right-k+1, right], so index i is stale when i <= right - k. Writing q[0] < right - k keeps the index exactly k behind. On nums = [5, 1, 1], k = 2 that produces [5, 5] instead of [5, 1]: at right = 2 the deque is [0, 2] and index 0 is out of the window. Detect it with a brute-force O(nk) differential test over random arrays containing duplicates and negatives, plus k = 1 and k = n.

Recording before evicting. Emitting nums[q[0]] before the eviction step reports the same expired index: [5, 1, 1], k = 2 gives 5 at right = 2 from index 0. The order is purge → push → evict → emit.

Storing values instead of indices. You then cannot tell when the front expires, and two equal values from different windows are indistinguishable. Store indices and compare nums[...].

<= vs < in the purge. This does not change the output, the front is the window maximum either way, but < keeps equal values, so the deque holds up to k entries instead of collapsing runs of duplicates. <= is the tighter choice; don't expect a correctness difference.

k == 1 shortcut aliases the input. return nums hands back the caller's own list; a caller that mutates the result mutates the input. Use list(nums) if that matters.

k > n returns [] silently. LeetCode guarantees k <= n, so this is a policy choice rather than a bug, but a caller expecting an error won't get one.

Complexity and Trade-Offs

  • Time: O(n). Each index is appended once and popped at most once, so total deque modifications are at most 2n: O(1) amortised per iteration.
  • Space: O(k) auxiliary, excluding output, since the deque holds at most k in-window indices.
  • Alternative (max-heap): push (val, idx) and lazily discard entries whose index is out of the window. That is O(n log n) time and allocates a node per element; the deque wins on both, and the heap only makes sense if you also need order statistics the deque can't give you.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

What would you measure before treating the monotonic deque for window maxima as settled?

Answer

Assumptions first. n (stream length), k (window), value distribution, runtime, and whether this loop is on the hot path at all. If n = 10^4 and k = 5, the deque is a curiosity; if n = 10^8 and k = 10^4, the naive scan is 10^12 comparisons and the deque is the only option. So measurement zero is a profile of the caller: is window-max even the bottleneck?

1. Differential correctness. Run the deque against brute-force max(a[i:i+k]) on random ints, all-equal, strictly increasing, strictly decreasing, k=1, k=n, and negatives. Acceptance: zero mismatches over 10^5 random cases plus the adversarial set. This is the test that catches the value-vs-index bug: store values and you cannot tell when the front left the window, so the max goes stale. It survives casual testing because the happy path hides it.

2. The crossover k. The deque is O(n) with a fat constant: a data-dependent while-loop plus append/popleft. The naive scan is O(nk) with a thin constant. Measure both at fixed n across k = 1, 2, 4, 8, 16, 32, 64 and find where they cross. Hypothetical on CPython 3.12, n = 10^6: naive wins below roughly k ≈ 8–16; the deque wins above. Below the crossover, "linear time" is the slower answer.

3. Allocation and memory. In Python every stored index is a boxed int: a deque of k indices is ~8 bytes pointer + ~28 bytes int object per slot. At k = 10^4 that is ~360 KB of live objects versus ~80 KB for a ring buffer of raw ints. In C++ std::deque allocates in chunks; a fixed ring buffer of size_t is one allocation. Measure RSS and allocation count.

4. Tail latency and branches. The pop loop is amortized O(1) but a single step can pop up to k elements: worst single step is O(k). Measure p50/p99/p999 of per-element cost, not the mean, and check perf stat branch-misses on the while condition. If p99 is the SLO, the amortized argument does not cover it.

Acceptance criteria I would write down: 0 mismatches on the adversarial suite; throughput ≥ naive at the production k; p99 per-element ≤ budget; RSS within budget. Only then is it settled.

The artefact under test:

Python
from collections import deque
dq, out = deque(), []
for i, v in enumerate(a):
    while dq and a[dq[-1]] <= v: dq.pop()   # evict by value from the back
    dq.append(i)
    if dq[0] <= i - k: dq.popleft()         # evict by position from the front
    if i >= k - 1: out.append(a[dq[0]])

Trace on a = [1, 3, -1, -3, 5, 3, 6, 7], k = 3: the deque holds indices in decreasing value order; at i=4 the entering 5 pops a[3]=-3, a[2]=-1, a[1]=3, leaving [4]; output is [3, 3, 5, 5, 6, 7]. Each index is pushed once and popped once: that is the O(n) claim, and it is exactly the claim the crossover and tail-latency measurements test.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does the amortised argument force that a junior answer usually skips?

Answer

The amortised argument buys a bounded total and pays for it with three things a junior answer leaves out: no bound on any single step, no room to move a boundary backwards, and no reuse across passes. It is a claim about the sum of work over one pass, not about the shape of the work inside it.

The counters make it exact. right advances once per element; left advances at most once per element across the whole run. So at most 2n pointer moves, but that ceiling is on the total, and one iteration may spend almost all of it.

Python
# Python 3.12. Longest subarray of a with sum <= S, all a[i] >= 0.
def longest_at_most(a, S):
    left = total = best = moves = 0
    for right, x in enumerate(a):
        total += x
        while total > S:          # can run many times in one iteration
            total -= a[left]
            left += 1
            moves += 1
        best = max(best, right - left + 1)
    return best, moves

Trace it the way the interpreter runs it, on a = [1, 1, 1, 1, 100], S = 3:

  • right=0: total=1, best=1. right=1: total=2, best=2. right=2: total=3, best=3.
  • right=3: total=4, so one trip through the while: total=3, left=1, moves=1. best stays 3.
  • right=4: total=103, so total=102 left=2 moves=2; total=101 left=3 moves=3; total=100 left=4 moves=4; total=0 left=5 moves=5. best = max(3, 4-5+1) = 3.

Result: (3, 5). The bound allows up to 2n = 10 moves here and the run used 5, yet the last iteration alone did 4 of them. Scale that: with n = 10^6 and one large trailing element, that single iteration performs roughly 10^6 moves while every other iteration performs one. Linear total, unbounded per-step cost.

That is the trade you are accepting, and the alternatives are decided by which of the two bounds your contract actually sells:

ApproachTotal workWorst single stepExtra cost
Two pointersO(n)Theta(n)O(1) memory
Recompute each windowO(n*k)Theta(k)no memory, n*k work
Monotonic deque (window max/min)O(n)Theta(k) pops, O(1) read of the frontO(k) memory
Segment treeO(n) build, O(log n) per querybounded per queryO(n) memory, most code
Sparse tableO(n log n) build, O(1) per querybounded per queryO(n log n) memory

Take two pointers when the contract is batch throughput and one slow step is harmless. Take a deque or a segment tree when the contract is a per-request latency bound: an event loop performing one window advance per request meets the Theta(k) step as a genuine tail event. As a hypothetical, if the swap-out body averages 2 us per element, a 10^4-element sweep is a 20 ms request against a 1 ms budget, and the mean never shows it.

Two failure modes worth naming. First, backtracking: any assignment that sets left below its current value breaks the argument, and it usually arrives as a "retry the window" branch. It hides because ordinary inputs never enter that branch. Detect it with an assertion that left is non-decreasing, and a counter that fails the run when moves > n. Second, a non-monotone predicate: the shrink loop assumes removing from the left can only restore validity. With negatives that is false. For a = [5, -4, 1] and S = 4, the correct answer is 3, since the whole array sums to 2, but the two-pointer returns 2 because it already discarded the 5. Detect it by diffing against a brute-force O(n^2) implementation on small random inputs that include negatives.

Skip the pattern when the window needs arbitrary subrange queries, when prior work must be undone (persistence, versioning, reprocessing), or when the predicate is not monotone in the boundaries. In those cases the amortised argument does not run slowly; it is wrong.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How does why a heap is the wrong structure here change if the workload grows by two orders of magnitude?

Answer

Pin down what 'here' means first, because the answer turns on it. The structure in question is the sliding-window maximum: a stream of n int64 values, a fixed window of k, emit the max of the last k at every step. A monotonic deque does that in amortized O(1) per element and holds at most k entries. A binary heap does it in O(log n) per element and, unless the input cooperates, holds n entries. Growing the workload 100x changes neither asymptotic. What it changes is the arithmetic: the heap goes from wasteful to impossible, and the deque does not move at all.

The arithmetic

Assumptions: CPython on 64-bit, k = 10,000, values are 8-byte int64.

propertymonotonic dequeheap + lazy deletion
entries held, best case<= k~k
entries held, worst casekn
bytes per entry~36 (28-byte int object + 8-byte deque slot)~128 (56-byte tuple + two int objects + 8-byte list slot)
total at n = 1e6~360 KB~128 MB
total at n = 1e8~360 KB~12.8 GB
comparisons per elementamortized O(1)O(log n): 20 levels -> 27 levels

Two orders of magnitude on n move the heap's worst case from 128 MB, which fits and is merely wasteful, to 12.8 GB, which is dead on a 16 GB node once the input array and the interpreter share the box. The deque stays around 360 KB, because its size is a function of k and not of n. That is the whole of how the reason changes: at the smaller scale the heap is a defensible constant-factor loss; at the larger one it is a memory failure waiting for the right input.

The worst case is reachable, not theoretical

Sorted-ascending input triggers it. The newest value is always the largest, so it is always the heap top, so the top is never out of range, so nothing is ever popped and the heap grows to n.

Python
import heapq

def lazy_window_max(a, k):
    h, out = [], []
    for i, v in enumerate(a):
        heapq.heappush(h, (-v, i))          # max-heap via negation
        while h[0][1] <= i - k:             # top has fallen out of the window
            heapq.heappop(h)
        out.append(-h[0][0])
    return out

Trace it with k = 3 on a = [1, 2, 3, 4], watching heap length and whether the eviction loop fires:

ivheap length after pushpopsemit
01101
12202
23303
34404

Heap length equals the number of elements seen, which is n. The same code on a = [4, 3, 2, 1] pops on the last step and settles back to k:

ivheap length after pushpopsemit
04104
13204
22304
31413

Monotone counters, cumulative sums, ever-rising queue depths: the streams a sliding-window max is actually deployed on look like the first table.

Why 100x specifically

The log factor is not the story. log2(1e6) = 20 and log2(1e8) = 27, a 35% rise in comparisons. Memory traffic is the story. At 12.8 GB the heap is nowhere near cache, so each of the 27 sift levels is likely its own cache line and its own DRAM miss, an estimated 80-100 ns each, which puts a push on the order of 2 microseconds. The deque's ~360 KB ring stays resident in L2 and each step touches one or two lines. Treat those microsecond figures as an estimate to confirm with perf stat or a per-record plot of RSS against elapsed time, not as a measured number.

Detecting it before production

Watch resident memory against n rather than wall-clock time; the metric that moves is RSS tracking stream length instead of window size.

Log heap length at p50 and p99. If p99 grows with n, the input has long ascending runs.

Shuffled test data hides this. Random input pops the old maximum early, so a unit test over a random array shows the heap holding O(log n) entries and passes. Add sorted-ascending and descending arrays to the test set.

The failure is silent on correctness: every emitted maximum is right. Only memory and tail latency are wrong.

When the heap is still the right call

If the eviction rule is not positional - TTL expiry, evict-by-key, top-k with arbitrary removal - the deque does not apply. Lazy deletion is a stopgap there. The structure you want is an indexed heap: a binary heap plus a dict from key to array position, giving O(log n) deletion and keeping the heap the size of the live set. Growth by two orders of magnitude still bites the log factor, but O(n) memory is inherent to that requirement, so budget for it explicitly instead of discovering it as an OOM at 3am.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Describe monotonicity is a precondition and the evidence you would collect before relying on it.

Answer

The 90-second answer

Monotonicity is the precondition that makes the two-pointer shrink step sound: if a window violates the constraint, every window containing it also violates it. When that holds, an invalid window has exactly one repair, drop elements from the left, and the longest valid window ending at index r is the one with the smallest left edge. For "longest subarray with sum ≤ K" it holds exactly when every value is non-negative, because adding a non-negative element can only raise the sum. It fails the moment a negative value is allowed: adding an element can lower the sum, so an invalid window can become valid by growing.

Why it holds, and where it breaks

The predicate is monotone in the window's element set. Sums of non-negative values, counts of distinct elements, bitwise OR, and max all move one way as you add elements. Sums with mixed signs and "average ≤ K" do not. The two-pointer's correctness argument is: for each r, the smallest l with [l, r] valid gives the longest valid window ending at r. That argument needs shrinking to never turn a valid window invalid. Non-negative sums satisfy it; mixed signs don't.

The break, traced

a = [6, -2, 1], K = 5, longest subarray with sum ≤ 5.

Python
def longest_le_k(a, k):
    l = 0
    total = 0
    best = 0
    for r, x in enumerate(a):
        total += x
        while total > k:          # shrink from the left
            total -= a[l]
            l += 1
        best = max(best, r - l + 1)
    return best

print(longest_le_k([6, -2, 1], 5))   # prints 2

Trace: r=0, total=6 > 5, so l moves to 1 and the window is empty, best=0. r=1, total=-2, best=1. r=2, total=-1, best=2. The function returns 2. The true answer is 3: [6, -2, 1] sums to 5. The greedy never considers it because at r=0 it discarded the 6 that the later -2 would have paid for.

Evidence before relying on it

  1. A domain argument that the aggregate is monotone under adding elements. State it in the code comment or the design doc; if you can't, you don't have the precondition.
  2. A differential test against an O(n²) brute force on random small inputs, with the generator deliberately including negative values and zeros. This is the test that catches the break above; a generator of positive ints never will.
  3. An in-loop assertion of the invariant you actually depend on: for non-negative inputs, assert total never decreases as r advances, and assert that after the shrink loop total <= k. Both fire on the first negative value.
  4. If the constraint is data-dependent rather than arithmetic (a rate limit, a quota), log the cases where shrinking failed to restore validity: those are the windows where the precondition was violated in production.

When not to use it

If values can be negative, use prefix sums with a hash map for "sum = K" (O(n) expected), or a monotonic deque over prefix sums for "sum ≥ K" with a minimum-length objective. If the constraint is a max or a distinct-count, monotonicity usually survives and the two-pointer is fine.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

What does the window validity invariant guarantee, and what does it deliberately leave open?

Answer

Core answer (first 90 seconds)

The invariant is: at the moment you read the answer, the window [left, right] satisfies the constraint. That is the whole guarantee. Every recorded candidate is a valid window, so the answer is never an overcount. It deliberately leaves three things open: whether the window is the largest valid one, whether validity is even restorable by shrinking, and how far you shrink. All three are assumptions you supply, not properties the invariant hands you.

Mechanism

The loop body has three jobs in order: extend right, restore validity by advancing left, then record. The shrink step is what restores the invariant after an extension breaks it, so the answer is read after shrinking, never before.

Python
def longest_unique(s):
    last = {}
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1          # restore: jump past the duplicate
        last[ch] = right
        best = max(best, right - left + 1)   # record after restore
    return best

Trace on s = "pwwkew":

rightchwindow after restorebest
0p"p"1
1w"pw"2
2w"w" (left jumps to 2)2
3k"wk"2
4e"wke"3
5w"kew" (left jumps to 3)3

Returns 3. At right=2 the restore jumps left straight to 2: the maximal valid window ending at 2 is "w", not "ww".

What it leaves open

  1. Maximality. The invariant says the window is valid; it does not say it is the longest valid window ending at right. You get maximality only because the shrink stops at the first valid left. Shrink one step too far and you drop candidates; record before shrinking and you keep invalid ones.

  2. Monotonicity. The invariant assumes shrinking can restore validity: that removing from the left never makes a valid window invalid. For a monotone constraint (distinct characters, sum ≤ K, at most K distinct) that holds. For a non-monotone one (sum exactly K, even length) it does not, and the shrink loop cannot restore the invariant at all.

  3. The shrink policy itself. You can trade the strict validity invariant for a weaker length invariant. The "at most K distinct" variant uses if instead of while:

Python
for right, ch in enumerate(s):
    count[ch] = count.get(ch, 0) + 1
    if len(count) > k:
        count[s[left]] -= 1
        if count[s[left]] == 0:
            del count[s[left]]
        left += 1
    best = max(best, right - left + 1)

Here the window is not always valid mid-run, it can hold K+1 distinct characters, but its length never decreases, so the final length is still the answer. This is O(n) with a weaker invariant: correct for the length, wrong if you need the actual window contents.

Failure modes

  • Recording inside or before the shrink step reports an invalid window, so the answer is too large. Casual tests miss it because the happy path often never triggers a shrink.
  • Using the if-shrink variant when you must return the substring, not its length, returns an invalid window.
  • Applying the pattern to a non-monotone constraint leaves the shrink loop unable to restore validity: it either never terminates or returns a wrong answer.

Deciding criteria: if you need the window contents, or the constraint is non-monotone, keep the strict invariant and shrink with while. If you only need the length and the constraint is monotone, the if-shrink variant is simpler and equally O(n).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

A vendor promises windows over streams is handled for you. What do you still own?

Answer

Core answer. The vendor owns the operator: assigning each element to a window, holding the per-key state, and firing when the watermark passes the window end. Everything that decides which elements land in which window, and what happens when they don't, is still yours. Four things, in the order an interviewer will probe them.

1. Time semantics and the timestamp. A window is meaningless until you say what clock it reads. Event time means you own the timestamp extractor: Flink's WatermarkStrategy.withTimestampAssigner, Kafka Streams' TimestampExtractor (default FailOnInvalidTimestamp, which throws on a missing timestamp rather than guessing), Dataflow's withTimestampFn. If you leave the default, you get processing time, and a 30-minute source backlog silently shifts every window.

2. The watermark and lateness policy. The vendor fires on the watermark; you decide how far behind it trails. Flink: WatermarkStrategy.forBoundedOutOfOrderness(Duration.ofSeconds(5)). Kafka Streams: TimeWindows.ofSizeAndGrace(Duration.ofMinutes(5), Duration.ofMinutes(2)). 3.x forces you to pick ofSizeWithNoGrace or ofSizeAndGrace explicitly. Dataflow: .withAllowedLateness(Duration.standardMinutes(2)). This number is a business decision: it is the maximum lateness you promise to account for.

3. State sizing and retention. Window state lives for window size + allowed lateness, per key. Retention must cover that span or late records find no window and vanish. Kafka Streams exposes it via Materialized.withRetention; Flink via state TTL and the RocksDB backend; Dataflow via the runner's state. You also own the key: a windowed aggregation over a high-cardinality key multiplies state by key count.

4. Sink semantics and replay. Exactly-once inside the pipeline (Kafka Streams processing.guarantee=exactly_once_v2, Flink checkpointing with two-phase-commit sinks) does not make your external sink idempotent. And you own the ability to replay the source with the same timestamps to backfill.

Owned by vendorStill yours
Window assignment, state storage, firingTimestamp extractor, time characteristic
Watermark propagationWatermark lag / allowed lateness
Per-key state backendRetention, key cardinality, state size
Internal exactly-onceSink idempotence, replay/backfill

Arithmetic. 5-minute tumbling window, 2-minute allowed lateness, 200 keys, 50 events/sec/key, 200 B of state per event. Per key per window: 50 × 300 = 15,000 events × 200 B = 3 MB. Live windows per key ≈ ⌈7/5⌉ = 2. Total ≈ 200 × 2 × 3 MB = 1.2 GB of window state, checkpointed. Drop allowed lateness to 0 and it halves; raise it to 10 minutes and it roughly doubles. That is the cost of the lateness promise.

Failure modes.

  • Watermark stall. One idle partition holds the watermark back; no window fires and latency grows without bound. Detect: Flink currentInputWatermark vs currentProcessingTime; Kafka Streams consumer lag per task. Fix: idle-source detection (withIdleness) or Flink 1.17+ watermark alignment.
  • Silent late drops. Records past the grace period are discarded. Detect: Flink numLateRecordsDropped, Dataflow droppedDueToLateness. Fix: route to a side output (sideOutputLateData) or dead-letter topic.
  • State blow-up. Retention longer than needed, or a hot key. Detect: checkpoint size / RocksDB size, Kafka Streams state-store metrics. Fix: shorten retention, salt the key.
  • Double writes on replay. EOS covers internal state, not a non-idempotent sink. Detect: sink-side dedup key or upsert semantics.

Trade-offs. Event time costs state and latency but survives backlog; processing time is cheap and wrong under replay. Accumulating mode re-emits the full result on each late element (downstream must handle retractions); discarding mode emits only the delta. Pick accumulating when the sink is an upsert, discarding when it is append-only. If you need per-element ordering or random access, windowing is the wrong tool: say so before proposing it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

When would you refuse a design because of time-based windows?

Answer

Refusal criteria. Assume a sliding window of raw events held in the serving process rather than a downsampled per-second counter. I refuse the design when any of these holds:

  • The ceiling is counted, not timed. A time window's cardinality is arrival_rate * span and has no bound of its own. If it feeds a fixed ring buffer, a per-tenant cache or an arena, there is no number anywhere in the design that memory cannot exceed.
  • The clock can move backwards. cutoff = now - span. After an NTP step back, a suspended VM or a leap-second smear, nothing expires and the window grows until the clock catches up; a step forward drops the whole window at once. I refuse anything that stamps events with wall clock instead of time.monotonic().
  • Event time comes from clients or peers. Seconds of skew are normal, and an event inserted at the back of a deque outlives its span because eviction only inspects the front.
  • Replay must be deterministic. The result then depends on when you read, not only on input order: a test that passed at 10:00 fails at 10:01.
  • Cost is per event, not per second. If each retained event costs a downstream call or a byte of quota, elapsed time meters the wrong quantity.

Where a time window is right. "At most 100 requests per rolling minute" is genuinely a time rule. So is an error rate over the last 5 minutes. So is a slow consumer that should catch up rather than lose the backlog a count-based eviction would discard.

Mechanism, with the overflow policy made explicit.

Python
import time
from collections import deque

class SlidingWindow:
    def __init__(self, span_s, cap, clock=time.monotonic):
        self.span, self.cap, self.clock = span_s, cap, clock
        self.q = deque()          # (monotonic_ts, item), oldest at left
        self.dropped = 0

    def offer(self, item, now=None):
        now = self.clock() if now is None else now
        cutoff = now - self.span
        while self.q and self.q[0][0] <= cutoff:
            self.q.popleft()                 # expired
        if len(self.q) >= self.cap:          # cap checked before append
            self.q.popleft()                 # overflow policy: drop oldest
            self.dropped += 1
        self.q.append((now, item))

Trace with span 60, cap 3. offer('a', 0): cutoff is -60, queue empty, length 0 < 3, append -> [(0,'a')]. offer('b', 10): cutoff -50, nothing expires, append -> [(0,'a'),(10,'b')]. offer('c', 20): cutoff -40, append -> [(0,'a'),(10,'b'),(20,'c')]. offer('d', 30): cutoff -30, nothing expires, length 3 >= 3 so drop (0,'a') and dropped becomes 1, append -> [(10,'b'),(20,'c'),(30,'d')]. offer('e', 65): cutoff 5, front timestamp 10 > 5 so still no expiry, cap forces drop of (10,'b'), dropped becomes 2 -> [(20,'c'),(30,'d'),(65,'e')]. Note what just happened: at 65 seconds the window should contain everything from the last minute, but 'c' and 'd' are the only survivors besides the new event. Time eviction and the count cap remove different things; dropping live events under load silently redefines the window as "the last 60 seconds, up to 3 events".

Alternatives.

StructureState boundClock-sensitiveUnder a burst
Sliding event windowrate * span, unboundedyes, monotonicgrows with the burst
Count window (ring of N)N, fixednotruncates the oldest history
Token bucket2 numbersyes, for refillburst up to bucket size, then rate
Time window + hard capmin(rate * span, cap)yes, monotonicoverflow policy must be stated

Failure modes and how they surface. Unbounded growth: window length and RSS climb together, so alert on length above span * expected peak rate and on the dropped counter leaving zero. Backwards clock: length rises with no traffic change; assert now >= last now and count violations. Stale client timestamps: a back-of-queue event lingers past its span; reject inserts whose timestamp falls outside [now - span, now].

So the refusal is never "time windows are unbounded". It is: you stated a ceiling this design cannot honour, and nobody has chosen which of the two guarantees yields. If no one will state the overflow policy, refuse and take the count window or the token bucket instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How does duplicate detection within a distance interact with rollback, and where do people ignore that?

Answer

Core answer (first 90 seconds). "Rollback" here is the eviction step: as the window slides forward, you undo the state that has fallen out of range. Duplicate detection within distance k is a fixed-size window over the last k elements, and the rollback is what keeps it fixed-size. The interaction that bites is ordering and identity: the rollback must remove the element that left by position, and it must run before the membership test. Get either wrong and you get a false positive at exactly distance k+1, or a window that grows without bound. People ignore this because the happy path (distinct values, or duplicates well inside the window) hides both.

The mechanism.

Python
def has_dup_within(a, k):
    window = set()
    for i, v in enumerate(a):
        if i > k:
            window.discard(a[i - k - 1])   # rollback: the element that left the window
        if v in window:
            return True
        window.add(v)
    return False

Trace a = [1, 2, 1], k = 1:

ivi > k?rollbackwindow before testv in window?window after
01no—{}no{1}
12no—{1}no{1,2}
21yesdiscard a[0]=1{2}no{2,1}

Returns False. The two 1s are 2 apart, which is > k=1, so that is correct. Move the test before the rollback and at i=2 the window is still {1,2}, 1 in window fires, and you return True for a pair that is out of range: a false positive at distance k+1.

The rollback-free formulation. Instead of undoing state, keep the last index of every value and compare:

Python
def has_dup_within(a, k):
    last = {}
    for i, v in enumerate(a):
        if v in last and i - last[v] <= k:
            return True
        last[v] = i
    return False

No eviction, and it hands you the pair (last[v], i).

ApproachPer-step costSpaceGives the pair?When it wins
Set of last kO(1) amortizedO(k)noboolean only, k bounded
Dict value→last indexO(1) amortizedO(distinct)yesyou need the pair, or k is large
Sorted window (balanced BST)O(log k)O(k)yes, plus order statsclosest-duplicate / range queries
Brute-force k-scanO(nk)O(1)yesk ≤ ~8, small n, no allocation

Failure modes.

  • Evict by value (window.discard(v)) instead of position: you remove the element you just inserted, the window grows, the answer is wrong. Detected by a test where the same value sits at both window ends.
  • Evict after the test: false positive at distance k+1. Detected by [1, 2, 1], k = 1.
  • If the detector is transactional, a duplicate aborts the surrounding transaction, the window state has to roll back with it. Skip that and the next transaction sees a stale window and reports a phantom duplicate. Detected by replaying the same batch twice and diffing the verdicts.

Pick the dict form when you need the pair or k is unbounded; keep the set form when you only need a boolean and k is small enough that O(k) space is free.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How would you review a pull request whose risk is empty and degenerate windows?

Answer

What I say first

The PR's risk is that the window bounds come from inputs the author never enumerated. I read the diff for three things: what the function returns when the window is empty, what it does when the requested window is larger than the input, and whether the shrink condition can produce a window of size zero. Then I check the tests actually cover those.

The two shapes

Empty window: the input is empty, or k is 0, or the shrink loop has already consumed everything. The loop body never runs, so the return value is whatever the accumulator was initialised to. That initialiser is the whole answer.

Degenerate window: k == 1, k == n, or k > n. The first two are legal and the loop simply doesn't iterate; k > n is a contract violation and the code has to say so.

Python
def max_sum(a, k):
    if k <= 0 or k > len(a):
        return None          # contract violation, not a value
    window = sum(a[:k])
    best = window            # first element, not 0
    for i in range(k, len(a)):
        window += a[i] - a[i - k]
        best = max(best, window)
    return best

Trace it (Python 3):

  • max_sum([], 3) -> k > len(a) -> None.
  • max_sum([5], 1) -> window = 5, range(1, 1) is empty, returns 5.
  • max_sum([5], 2) -> None.
  • max_sum([-3, -1, -2], 1) -> window -3, best -3; i=1 window -1, best -1; i=2 window -2, best -1. Returns -1. With best = 0 it returns 0, which is not a subarray sum.

What I'd push back on

best = 0 is the classic bug: correct on every test with a positive window, wrong on all-negative input. The mirror image is best = float("-inf") with no guard: it leaks -inf to the caller on empty input.

For the guard, the choice is between raising, returning a sentinel, and clamping. Raise when k out of range is a caller bug you want surfaced in CI. Return a sentinel when the caller legitimately queries an empty range and the aggregate has an identity (0 for sum, -inf for max). Clamping k to [1, n] is the one I'd reject: it silently answers a different question than the caller asked.

For variable-size windows, check the shrink condition. while window_sum > target: left += 1 can leave left == right, an empty window, and if the problem requires a non-empty window, that's a bug the tests won't catch unless they include a target smaller than every element.

Detection

Property test against a brute-force O(nk) reference over arrays that include empty, single-element, all-negative, and k in {0, 1, n, n+1}. Assert the guard's behaviour explicitly rather than letting it fall through.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What is the smallest experiment that would change your mind about windows with a shrink budget?

Answer

Two elements. The smallest experiment that would change my mind is a two-element array, [1, -1], with budget k = 0. One line to run, and it falsifies the claim I'd otherwise be leaning on.

The claim under test, stated before anything runs: if the window's cost is monotone in window length, the extend-and-shrink loop is correct. Assume the budget is on the window's sum and we want the longest window whose sum is at most k.

Python
def loop(a, k):                  # shrink while the window sum exceeds k
    cost = left = best = 0
    for right, v in enumerate(a):
        cost += v
        while cost > k:
            cost -= a[left]
            left += 1
        best = max(best, right - left + 1)
    return best

def brute(a, k):
    best = 0
    for i in range(len(a)):
        cost = 0
        for j in range(i, len(a)):
            cost += a[j]
            if cost <= k:
                best = max(best, j - i + 1)
    return best

print(loop([1, -1], 0), brute([1, -1], 0))

Trace of loop([1, -1], 0): right=0, v=1, cost=1 > 0, so drop index 0. Cost becomes 0, left=1, best stays 0. right=1, v=-1, cost=-1, no shrink, best = 1-1+1 = 1. It prints 1 2.

inputkloopbrute
[1]000
[-1]011
[1, -1]012

Length 1 agrees; length 2 disagrees. So the counterexample is minimal, and the trace shows why: the window [1] costs 1, and extending it with -1 drops the cost to 0. Monotonicity is the only thing that makes shrinking safe. When extension can repair a window, the loop discards valid windows and under-reports.

If I wanted one run that settles the family instead of one case, exhaustive differential testing is still cheap:

Python
from itertools import product
bad = [(a, k) for n in range(1, 4) for a in product((-1, 0, 1), repeat=n)
       for k in (0, 1) if loop(a, k) != brute(a, k)]
print(len(bad), bad[:3])

That is 39 arrays across lengths 1-3, times 2 budgets, 78 pairs. It prints 7 [((1, -1), 0), ((0, 1, -1), 0), ((1, -1, -1), 0)]. It covers every input up to length 3, including k=0 where the shrink branch fires on almost every step. It proves nothing about length 4 and nothing about costs that are non-monotone in a subtler way, which is exactly what the two-element case is there to remind me of.

What would not change my mind: a green run where the shrink body never executed (all-positive input, or k at least the total sum). That is coverage zero. Count shrink hits and check the counter is non-zero before trusting the result. A latency measurement is also not evidence; it answers a different question.

The decision rule that falls out: before using the pattern, check that cost is non-decreasing under extension. Do it by hand on one pair, a window W and W plus one element, or as a property test in CI that generates random windows and asserts cost(W) <= cost(W + [x]) for every x. Constraints that survive are the ones where the only way to blow the budget is to add elements: flips to k zeros, distinct-character count. Constraints that fail need enumeration instead of a shrink rule: longest subarray with sum at most k when values can be negative is the standard one, and it is solved with prefix sums and a monotonic deque, not by shrinking.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of windows on two dimensions?

Answer

Inject two grids, not one.

  1. A stale spike: a large value in the top row that dominates the first window, with only small values below, and enough rows that the spike scrolls out of the vertical window.
  2. A non-square window (k rows x m columns, k != m).

The first catches the expiry bug in a hand-rolled 2-D deque; the second catches a hardcoded square assumption.

Why the two-pass is correct. For a k x k block, max over the block = max over the k rows of (max over the k columns in that row). So a horizontal 1-D sliding max on every row, then a vertical 1-D sliding max on the result, gives the 2-D answer. Each 1-D pass is O(n) with a monotonic deque, so the whole thing is O(RC) time and O(R(C-k+1)) space for the intermediate.

Python
from collections import deque

def sliding_max_1d(nums, k):
    dq = deque()          # indices, values non-increasing
    out = []
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()
        dq.append(i)
        if dq[0] <= i - k:      # front fell out of the window
            dq.popleft()
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out

def sliding_max_2d(grid, k):
    rows = [sliding_max_1d(row, k) for row in grid]   # pass 1: horizontal
    w = len(rows[0])
    cols = [[rows[r][c] for r in range(len(rows))] for c in range(w)]
    out_cols = [sliding_max_1d(col, k) for col in cols]  # pass 2: vertical
    h = len(out_cols[0])
    return [[out_cols[c][r] for c in range(w)] for r in range(h)]

Trace on the stale-spike grid, k=2:

grid = [[9, 9],
        [1, 1],
        [1, 1]]

Pass 1, each row -> its 2-wide max: [[9], [1], [1]]. Pass 2 on the single column [9, 1, 1]: i=0 keeps 9; i=1 emits 9; i=2 pops the stale 9 (front index 0 <= 2-2) and emits 1. Result [[9], [1]]. The second window's answer is 1, and 9 is not in rows 1-2: that is the detection signal.

A buggy incremental 2-D deque that expires by value, or that only checks the front of the column deque, keeps the 9 and returns [[9], [9]]: the second window reports a maximum that is not in the window. That is the failure to inject.

Trade-offs. Direct 2-D incremental maintenance is also O(R*C), but the expiry bookkeeping is where the bugs live: column-deque entries must be expired by row index, and the row leaving the vertical window is often not at the front of the deque. The two-pass keeps each stage a plain 1-D problem you can test alone. Direct 2-D wins only when the grid is updated between queries and you cannot afford to redo the row pass; for a static grid, two-pass wins.

Cost. For a 1000x1000 grid and k=100: two-pass does about 2 x 10^6 deque operations. Recomputing each window from scratch is RCk^2 = 10^10. That gap is why the decomposition is worth knowing.

Other failures worth injecting: k=1 (identity), k larger than a dimension (empty result), and an all-equal grid (catches strict vs non-strict comparison in the deque).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How should on-call treat an alert that names prefix sums as the alternative as the cause?

Answer

First two minutes on the bridge

An alert that names prefix sums is naming where the number came from, not why it is wrong. A prefix sum is a derivation (a cumulative counter, a running-total column, a rate() over a monotonic series) and a derivation is not a cause. Treat the annotation as a hypothesis to confirm or refute, not a diagnosis to act on. Say that on the bridge: "the alert blames prefix sums; that's the mechanism, I'm checking whether the underlying series actually moved."

Then answer three questions in order. Is the alert on the raw series or the derived one? Did the raw series move? If the raw series is flat and only the derived one moved, the fault is in the derivation, and the blast radius is whatever reads that derived series: dashboards and downstream alerts, not customers.

The three ways a prefix sum produces a false page

What changedRaw seriesDerived seriesReal incident?
Counter reset (pod restart)drops to 0rate() spikeNo: reset artifact
Out-of-order backfillunchangednon-monotoneNo: data job
Genuine traffic shiftrisesrisesYes

Prometheus rate() assumes a decrease is a counter reset and extrapolates across it, so a restarting pod can look like a traffic spike on the derived series while the raw counter is doing exactly what it should.

Trace the backfill case

A running-total column maintained as running = previous_running + delta:

day  delta  running
1    100    100
2     50    150
3     20    170

A late delta of 30 arrives for day 2. The job recomputes only the touched row: day 2 becomes 100 + 80 = 180. Day 3 still reads 170, because nothing recomputed it. The series is now 100, 180, 170: it decreases, and the "running total must be non-decreasing" alert fires. The annotation is right about the mechanism and wrong about the cause: the cause is the out-of-order write, and the fix is recomputing the tail, not touching the alert.

Failure modes and how you catch them

  • Partial reset: a counter drops but not to zero (a shard restarting mid-window). rate() still treats it as a reset and can emit a spike. Detect by comparing the derived series against a recomputation from raw events over the same window; if they disagree, the derivation is lying.
  • Silent staleness: the derived series stops updating but keeps its last value, so it looks healthy. Detect with a freshness check on the derivation job's own heartbeat, not on the value.
  • Alert on the derived series only: you page on artifacts forever. Where the raw series exists, alert on it and keep the derived one for dashboards.

When the named cause is right

If the raw series genuinely moved and the prefix sum is simply how it is exposed, it is a real incident: page, and the annotation is a useful pointer to which aggregation to look at first. The distinction is always the same: did the input move, or only the accumulation of it? Confirm that before you wake anyone else. If you cannot tell within a few minutes, escalate with the raw-versus-derived comparison attached, because that comparison is the whole triage.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How would you brief product on why window state that is not a simple aggregate delays a ship date?

Answer

Open with the decision, not the mechanism. In the first two minutes I'd say: "The peak-sessions metric you asked for is a maximum over a 5-minute window. Our pipeline updates window state incrementally: it adds events as they arrive and subtracts them as they age out. That works for sums and counts, because subtraction is exact. It does not work for a maximum: when the peak leaves the window there is nothing to subtract. So we either recompute the window on every slide, or we build a new structure that tracks the maximum. Both cost days that were not in the estimate. Here is the choice and what each one costs."

Assumptions I'd state out loud before the options: window size and slide interval, event rate, whether an approximate peak is acceptable to product, and whether the ship date is fixed or the scope is.

Why the incremental path is wrong, in one snippet.

Python
total -= a[left]                 # exact inverse: sums are removable
if running_max == a[left]:       # no inverse: the previous maximum is unknown
    running_max = max(a[left + 1:right + 1])   # O(k) recompute

A running maximum looks correct until the peak element leaves the window. It survives casual testing because you need a peak followed by a decline to expose it: the input ordering that would catch it is exactly what a quick check leaves out. Detection is cheap once you know: assert the incremental result equals a naive recompute on random windows in CI.

The two correct implementations, traced. Naive recompute over a = [3, 1, 4, 1, 5], k = 3:

right=2  window [3,1,4] -> 4
right=3  window [1,4,1] -> 4
right=4  window [4,1,5] -> 5
out = [4, 4, 5]        # 3 slides x 3 elements = 9 comparisons

Monotonic deque, same input, same output [4, 4, 5]: each element is pushed once and popped at most once. 5 pushes and 4 pops for the whole array, amortised O(1) per event.

The table I'd put in front of product. Estimates are hypothetical, sized for this team:

OptionCorrect?Build costRuntime costWhat product sees
Keep running maxNo0lowestwrong peaks after the max ages out
Recompute per slideYes~1 dayO(k) per slideunchanged number
Monotonic dequeYes~3–5 days incl. tests and backfillamortised O(1) per eventunchanged number
Approximate sketchApproximate~2 dayslowpeak becomes an estimate

The arithmetic that decides it. At 2,000 events/s and a 5-minute window, one window holds 600,000 events. With a 1-second slide there are 300 slides per window, so naive recompute does 300 × 600,000 = 180M comparisons per 5 minutes: about 600k comparisons/s for this one metric. The deque does 2,000 operations/s. That 300× gap is the difference between "fits in the existing worker" and "needs its own consumer."

The ask. I'd recommend the deque, name the 3–5 days, and ask product to either move the date or cut scope. If the date is immovable, the approximate sketch is the honest fallback, and I'd say plainly that the peak becomes an estimate, not a count.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you document recognising the pattern so the next owner can operate it?

Answer

The doc has to be executable, not prose. A next owner should be able to run the recognition test, not read a paragraph about it.

Recognition test, as a table they check against the ticket:

SignalWindow appliesAlternative
Answer is a contiguous range (subarray, substring)yes—
Constraint moves one way as the range grows (sum only increases, distinct count only increases)yes—
Values can be negative, so sum is not monotone in lengthnoprefix sums + hash map
Elements need not be adjacent (subsequence)noDP / patience sorting
Fixed-size range, need max/min per positionyesmonotonic deque

Invariant, written where the loop is:

For "longest subarray with sum ≤ k, all values positive": total == sum(nums[left:right+1]) and total <= k after the shrink loop. The shrink is while, not if: one step is not always enough.

Precondition guard, so the wrong input fails loudly instead of quietly:

Python
def longest_at_most(nums, k):
    if any(x < 0 for x in nums):
        raise ValueError("sliding window needs non-negative values; use prefix sums")
    left = total = best = 0
    for right, x in enumerate(nums):
        total += x
        while total > k:
            total -= nums[left]
            left += 1
        best = max(best, right - left + 1)
    return best

Trace on [2, 1, 3, 1], k=4: right=0 total=2 best=1; right=1 total=3 best=2; right=2 total=6, shrink nums[0]=2 → total=4, left=1, best stays 2; right=3 total=5, shrink nums[1]=1 → total=4, left=2, best stays 2. Returns 2: [2,1], [3,1] and [1,3] all qualify, none longer.

Failure modes and how the next owner detects them:

  • Window on negative values: silently wrong, and small examples often pass. Detection: the guard above, plus a property test. 1000 random arrays of length ≤ 12 with values in [-5, 5], compared against the O(n²) brute force. It fails on the first run.
  • Window on a subsequence problem: elements need not be adjacent, so the shrink step drops candidates it cannot recover. Detection: check the statement for "subarray/substring" versus "subsequence" before writing code; the table above is that check.
  • Doc rot: the table drifts from the code. Detection: keep the guard in the code and the table beside it in the same file, so a change to one surfaces in review of the other.

What to hand over: the table, the guarded function, and the brute-force cross-check as a test. The next owner runs the test, reads the guard, and knows which technique to reach for when the guard fires.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

What would you ask a candidate who recites windows in production systems but cannot apply it?

Answer

The question I'd ask

"1,000 requests per minute per API key, enforced inline in the request path, Redis-backed, 1M active keys. Pick the data structure and tell me what it costs. Then: one key sends 1,000 requests in the last second of a minute and 1,000 in the first second of the next. Did it exceed its limit?"

That is the whole first question. It names a guarantee, forces a structure choice, and the boundary case is where recitation and understanding separate.

Why it discriminates

A reciter names the algorithms (fixed window, sliding window log, sliding window counter, token bucket) and says the sliding log is "more accurate." A practitioner asks what the limit protects (capacity, fairness, or cost) and what the memory budget is, because those decide the structure. The reciter answers the definition; the practitioner answers the system.

Follow-ups, in order

  1. "What does the sliding window log hold in memory at 1M keys?": 1,000 timestamps per key × 1M keys = 1e9 entries. A Redis sorted-set entry costs roughly 100 bytes (member, score, skiplist pointers, dict entry), so ~100 GB. A fixed-window counter is one integer plus a TTL per key: call it 100–200 bytes per key, so ~100–200 MB for the same 1M keys. That gap is the whole design decision.
  2. "The boundary case: did it violate?": A fixed window aligned to the minute counts 1,000 in each bucket, so both pass: 2,000 requests in a 2-second span, 60x the 16.7 req/s the limit implies. A sliding window log rejects the second batch, because at 12:01:00.5 all 2,000 timestamps fall inside the trailing 60 s.
  3. "You want the log's accuracy without the memory. What do you build?": Weighted sliding window counter: two fixed-window counters, the previous one discounted by how much of it still overlaps. At 12:01:00 the previous window still weighs 1.0, so the estimate is 1,000 and the next request is rejected; by 12:01:30 the weight is 0.5, so ~500 more get through. It assumes requests spread evenly across the previous window, which is exactly wrong during a burst: that is the trade.
  4. "Redis is down. Allow or deny?": Fail open risks the overload the limiter exists to prevent; fail closed turns a cache outage into a full outage. The usual answer is a per-node local token bucket as a fallback, sized at limit/nodes, accepting that the global limit is approximate while Redis is gone.

What separates the two answers

ReciterPractitioner
Structure"Sliding window log, it's more accurate"Picks from the guarantee and the memory budget
Memory"It's O(n)"~100 GB for 1e9 log entries vs ~100–200 MB for counters
BoundaryDoesn't raise it2,000 requests pass a fixed window in 2 s
ClockNot mentionedUses Redis server time, not per-node wall clocks
Redis downNot mentionedLocal token bucket fallback, limit/nodes

The boundary row is the one I weight most. A candidate who spots the 2,000-in-2-seconds hole unprompted is modelling the limiter; one who does not has a definition.

What I'd accept

The senior answer is conditional: pick the structure from the guarantee, bound the dimension that can grow without limit, and say which part is a guarantee and which has to be measured. "Weighted sliding window counter, two counters per key, and I'd cap the key count with an LRU so a key flood can't blow up memory" is the answer I am listening for. So is "token bucket, capacity 1,000, refill 16.7/s, because the product actually wants to allow a burst."

Curated: · Written: · Reviewed:

Difficulty: Hard