Two pointers and the sliding window

100 min6 partsCoreFundamentalsChecked Nov 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Find a pair that hits a target in sorted data with one pointer at each end, and say why each step rules out a whole row or column of pairs
  • Slide a window of fixed size in O(1) a step, with a running sum or a Counter that takes in what enters and lets go of what leaves
  • Grow a window on the right and shrink it from the left while it breaks the rule, keep its state in a set, a dict of last positions or a Counter, and say why the whole pass is O(n)
  • Keep a window over time in a deque that drops what aged out, and build a rate limiter whose memory holds only the requests that still count
  • Answer the follow-ups: negative numbers and prefix sums, the largest value in every window, limits too big to log every request, and one limit across many machines
Part 1 of 6about 13 min
Two pointers

Windows over a request log

Netflix software engineer candidates report the longest substring without a repeated character in coding rounds (2 reports), once on an array of numbers (1 source), and it's on Netflix's LeetCode tag lists (2 sources). The practice problem sets it in an API gateway's request log:

An API gateway writes one entry per request: the key of the client that sent it, in the order the requests arrived. Keys are hashable values, strings in most tests. A run is a stretch of consecutive entries.

Write longest_distinct_run(keys) -> tuple[int, int]. keys is a list. Return (start, length) for the longest run in which no key appears twice, where start is the index of the run's first entry. When several runs tie for longest, return the one that starts first. An empty log returns (0, 0). Make it one pass: O(n) for n entries.

LogReturns
["ana", "bo", "cy", "ana", "dee", "eli", "bo", "fay"](2, 6)
["u3", "u7", "u3", "u1", "u9", "u7", "u2", "u1"](2, 5)
["u1", "u2", "u2", "u1"](0, 2), the first of two runs of 2
["ana", "ana", "ana"](0, 1)
[](0, 0)

Two more levels follow. Level 2 flags the entries whose client is also among the k requests just before, on a live stream you can read only once. Level 3 is a rate limiter: at most limit requests per client in any window seconds, with memory that holds only the requests that still count.

You don't write it yet. The lesson starts with two indexes on sorted data and builds the window one idea at a time. At the end you solve the whole problem, level by level, in an interview simulation with a 40-minute timer.

This lesson builds on hash maps: the window keeps a count of what's inside it in a dict. The same window, measured in seconds instead of positions, becomes a rate limiter here, and time windows come back in the database's level 3, in the coding builds, where small systems grow in levels.

Two indexes instead of two loops

A lot of coding questions ask about pairs or stretches of a list. Two files whose sizes add up to a target. The longest stretch of a log with no repeat. How many requests a client sent in the last ten seconds.

The first code that comes to mind tries every pair or every stretch: two nested loops, O(n²). This lesson swaps the two loops for two indexes that each move in one direction only. Each index takes at most n steps, so the whole pass is O(n).

The pieces build to the practice problem: three questions about an API gateway's request log. The first two-index trick works on sorted data.

On sorted data, start one pointer at each end

In the hash-maps lesson's worked example you found two files that fill a disk exactly, with a dict from size to position. That cost O(n) time and O(n) memory. When the sizes arrive sorted, you can drop the dict. Put lo on the smallest size and hi on the largest, and look at their sum:

# sizes sorted, low to high
def pair_with_sum(sizes, target):
    lo, hi = 0, len(sizes) - 1
    while lo < hi:
        total = sizes[lo] + sizes[hi]
        if total == target:
            return lo, hi
        if total < target:
            # sizes[lo] is too small even with the biggest partner left
            lo += 1
        else:
            # sizes[hi] is too big even with the smallest partner left
            hi -= 1
    return None

sizes = [100, 250, 300, 450, 700, 800, 1200]
print(pair_with_sum(sizes, 1150))
Predict

sizes are 100, 250, 300, 450, 700, 800, 1200, and the target is 1150. Which two add up to it?

Pick one to see what it prints.
Pick an answer above to see the rest

Each step rules out a whole row or column of pairs

Why is it safe to throw a value away after one comparison? Write every pair's sum in a grid:

Every pair's sum
sums
2503004507008001200100350400550800900130025055070095010501450300750100011001500450115012501650700150019008002000

Each cell adds its row's size and its column's size. The target, 1150, is 450 + 700.

The list is sorted, so the sums grow to the right along a row and down a column.

Step 1 looked at the top right corner, 100 + 1200 = 1300. That's too big. Every other cell in the 1200 column sits lower down, so it's at least 1300 too. The whole column is out, and hi -= 1 loses nothing.

Step 2 looked at 100 + 800 = 900. That's too small, and 800 is the biggest partner 100 has left. Every other cell left in the 100 row sits to its left, so it's smaller still. The whole row is out.

Every step works the same way:

The step that ruled out each pair, and * for the pair it found
step
2503004507008001200100222221250333313004441450*51700518001

Step 1 rules out the whole 1200 column, step 2 the 100 row, and so on.

Each step rules out a whole row or a whole column by moving one pointer one place. The pointers start n - 1 places apart, so the loop takes at most n - 1 steps.

Write moves on the same sizes. It runs the pointers the way pair_with_sum does and lists which one each step moved, so you can count the steps.

Sorted input: two pointers. Unsorted: the dict, unless memory is the constraint

Here are two pointers and the dict against checking every pair. The sizes are 0, 2, 4, ... and the target is odd, so no pair exists and every version must do all its work:

n, pairsEvery pair, msTwo pointers, msDict, ms
1,000, 499,50015.80.0460.051
2,000, 1,999,00064.50.0970.109
4,000, 7,998,000255.80.1850.209
8,000, 31,996,0001,036.30.3820.411

Python 3.12, best of several runs with timeit, on the laptop these numbers come from.

Two pointers and the dict are both O(n), and close in time. The difference is memory. On a million sorted sizes, the dict's peak was 78.66 MiB by tracemalloc, Python's memory tracer. Two pointers allocated under 0.01 MiB.

The catch is the word sorted. Sorting a million random integers took 139.8 ms, more than the dict's whole pass at 72.4 ms. Sorting also scrambles the original positions.

So: sorted input, two pointers. Unsorted input, the dict, unless memory is the constraint.

The editor holds the start of pairs_within, with lo and hi at the two ends of a sorted price list. Finish the loop so it counts a whole row of pairs after one comparison.

CheckpointCount a whole row at once

prices is sorted from low to high. Finish pairs_within(prices, budget): the number of pairs of positions i < j with prices[i] + prices[j] <= budget. When the cheapest price left fits with the most expensive one left, it fits with every price between them too, so count that whole row at once. The last test counts how many times you read prices, and code that checks every pair reads it far too often.

Part 1 done
Part 2 of 6about 8 min
A fixed window

A window of fixed size

Now the two indexes walk in the same direction. Say the gateway counts requests per minute, and a dashboard wants the total over every 3 minutes in a row.

One step right: one entry enters and one leaves

def window_sums(values, k):
    total = sum(values[:k])
    sums = [total]
    for right in range(k, len(values)):
        # one enters, one leaves
        total += values[right] - values[right - k]
        sums.append(total)
    return sums

per_minute = [12, 7, 9, 15, 4, 11, 8]
print(window_sums(per_minute, 3))
Predict

Counts per minute: 12, 7, 9, 15, 4, 11, 8. The first 3-minute window totals 28. What does the second total?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

On 100,000 counts with k = 1,000, summing every slice took 531 ms. About how long does the running total take?

Pick an answer above to see the rest

A Counter counts copies, so a key twice in the window stays counted

The state doesn't have to be a sum. It can be anything you can update when one entry comes in and one goes out.

How many different clients sent requests in each window of k? A set of keys looks right. Here it is next to a count per key, on the log ana, ana, bo with a window of 2:

Window of 2A setA Counter
ana, ana{ana}{ana: 2}
ana, bo{bo}: 1 key, wrong{ana: 1, bo: 1}: 2 keys, right

A key can be in the window twice, and a set doesn't know that. When the first ana leaves, removing it from the set forgets ana, while the second copy is still inside.

The window needs a count per key: a Counter. Add 1 for the key that enters, and take 1 off the key that leaves. Then len(counts) is the number of different keys, with one catch:

from collections import Counter

c = Counter(["ana", "bo", "ana"])
c["bo"] -= 1
print(c, len(c), "bo" in c)
Counter({'ana': 2, 'bo': 0}) 2 True

bo has left the window and is still a key. A count of 0 doesn't remove it. Delete a key when its count reaches 0, or len(counts) counts clients that are gone:

from collections import Counter

c = Counter(["ana", "bo", "ana"])
c["bo"] -= 1
if c["bo"] == 0:
    del c["bo"]
print(c, len(c))
Counter({'ana': 2}) 1

The editor holds distinct_per_window, with the first window already counted in a Counter. Write the updates inside the loop: the key that enters and the key that leaves.

CheckpointDistinct clients in every window

Finish distinct_per_window(keys, k): for every window of k consecutive entries, the number of different keys in it, from the first window to the last. The stub counts the first window. In the loop, add the key that enters, take away the key that leaves, and delete a key whose count reaches 0. The last test counts how often keys are hashed: a few hashes per step passes, and rebuilding the whole window each step doesn't.

Watch · 8 min

Greg Hogg works a fixed-size window: add the item that enters, drop the item that leaves, and never recount the middle.

Sliding Window Algorithm - Variable Length + Fixed Length - DSA Course in Python Lecture 13 · Greg Hogg · Jul 2024YouTube
Part 2 done
Part 3 of 6about 20 min
A growing window

Grow on the right, shrink from the left

Some windows don't have a size you know in advance. The practice problem's first level asks for the longest stretch of the log in which no client appears twice.

Netflix candidates reported it three times (3 sources), more than any other window question in this course's bank, and it's on Netflix's LeetCode company list (1 source). It's usually asked on a string: the longest substring without a repeated character. A string is a list of characters, so it's the same code.

Starting over at every index checks the same keys again

The obvious way starts a stretch at every index and extends it until a key repeats:

def longest_every_start(keys):
    best = 0
    for start in range(len(keys)):
        seen = set()
        for key in keys[start:]:
            if key in seen:
                break
            seen.add(key)
        best = max(best, len(seen))
    return best

log = ["u3", "u7", "u3", "u1", "u9", "u7", "u2", "u1"]
print(longest_every_start(log))
Predict

The log is u3 u7 u3 u1 u9 u7 u2 u1. What's the longest stretch with no key twice?

Pick one to see what it prints.
Pick an answer above to see the rest

The window grows on the right and shrinks while it holds a repeat

The window keeps that work. right moves forward one entry per step and adds it. If the new entry breaks the rule, left moves forward, removing entries, until the window is valid again.

In code, a set seen holds the keys in keys[left:right + 1], and left starts at 0. For each right and its key, a while key in seen loop removes keys[left] from the set and adds 1 to left. When that loop ends, the key isn't in the window any more, so add it to seen. The window now runs from left to right, and its length is right - left + 1. The longest of those lengths over the pass is the answer, 5 for this log.

Predict

The window is u3 u1 u9 u7 u2, and the u1 at index 7 comes in. Which keys does left drop to make the window valid?

Pick an answer above to see the rest

Left only moves forward, so the inner loop runs at most n times in all

A while inside a for looks like O(n²). Here it isn't. Count what happened to each entry in the trace above:

IndexKeyAdded atDropped at
0u302
1u715
2u327
3u137
4 to 7u9, u7, u2, u14 to 7never
in all8 adds4 drops

Each entry is added once, when right reaches it. It's dropped at most once, when left passes it, because left never moves back. So the inner loop runs at most n times over the whole pass, not n times per step. On a million random keys drawn from 1,000 clients, it removed 999,939 entries in total.

The whole pass is O(n) time, with memory for the keys in the window. Here it is on logs where every key is different, the worst case for starting over:

nEvery startWindow with a setWindow with last positions
1,00013.2 ms0.111 ms0.111 ms
2,00053.4 ms0.229 ms0.234 ms
4,000213.8 ms0.455 ms0.463 ms

Write drops: your loop from windows, with a counter in its while loop, so you see how many entries it removes over a whole pass.

Jump the left edge, but only past a copy still inside the window

The last column of that table is a second way to shrink. Instead of a set, keep a dict last from each key to the index where you last saw it.

When key repeats, the window must start just after its earlier copy. So left can jump to last[key] + 1 in one move, instead of stepping there. In the trace above, the u1 at right 7 was last seen at index 3, so left jumps from 2 to 4.

Predict

Log u1 u2 u2 u1. At index 3, left is 2, and last says u1 was at 0. If left jumps to last[u1] + 1, what window do you get?

Pick an answer above to see the rest

The same loop works whenever a broken window stays broken as it grows

Every variable window has this shape:

  1. Add the entry at right.
  2. While the window breaks the rule, remove the entry at left and move left forward.
  3. Now the window is valid. Record it.

Only the state changes with the rule:

  • No key twice: a set, or a dict of last positions to jump.
  • At most two different clients: a Counter. Shrink while len(counts) > 2, and delete keys at 0 as before.
  • Total at most a budget, with no negative numbers: a running sum. Shrink while it's over budget.

It works because of one property. Once a window breaks the rule, every longer window with the same left end breaks it too. Hold left at 0 on the log from before, and let right grow:

left stays at 0 while right grows
01234
u3u7
no repeat
u3u7u3
u3 twice
u3u7u3u1
u3 still twice
u3u7u3u1u9
u3 still twice

A stretch with a repeat keeps it when it grows. So once [left, right] breaks the rule, no window that starts at left can be the answer, and left can move on for good. The follow-ups at the end of this lesson come back to what happens when that property fails.

Now change the rule to at most two different clients. Write longest_two with the same three steps and a Counter of the window.

Watch · 7 min

The same window on the string version of the question, worked through and coded in Python, in under seven minutes.

Longest Substring Without Repeating Characters - Leetcode 3 - Python · NeetCode · Jun 2020YouTube
Part 3 done
Part 4 of 6about 23 min
Deques and rate limits

A deque holds a window you can't index

The practice problem's second level asks for the clients seen again within the last k requests. The log is a live stream: a generator you can walk once. You can't read keys[right - k] from a stream. You have to keep the last k keys yourself, adding at one end and removing from the other.

The third level, a rate limiter, goes further. It allows at most limit requests per client in any window seconds. So the window is measured in seconds, and how many entries it holds depends on the traffic.

Both need a queue: add at the back, take from the front.

A list takes from the front in O(n), a deque in O(1)

Here's what taking the first item does in each:

Taking the first item out
list.pop(0)
abcde
deque.popleft()
abcde

Red leaves. In the list, the 4 orange items behind it each move one place. In the deque, nothing else moves.

A Python list keeps its items side by side. Take the first one, and every item behind it shifts down one place. collections.deque, a double-ended queue, is built for both ends. Taking from its front moves nothing else.

Draining one of each:

Itemslist.pop(0) until emptydeque.popleft() until empty
100,0000.785 s2.9 ms
200,0003.153 s6.4 ms

Double the items and the list takes four times as long: O(n) per pop, O(n²) to drain. The deque's time doubles: O(1) per pop.

Three calls do the work here:

  • append(x) adds at the right.
  • popleft() takes from the left.
  • d[0] reads the oldest item without removing it.

Level 2's log arrives as a generator. Write last_k, which reads stream once and keeps only its last k keys in a deque.

On a stream, a deque and a Counter hold the last k keys

With a deque, the fixed window runs on a stream. Append the new key. Once the deque holds more than k, popleft() hands you the key that's leaving, so you can take it off the Counter:

from collections import Counter, deque

# keys can be a generator
def distinct_per_window_stream(keys, k):
    window, counts = deque(), Counter()
    for key in keys:
        window.append(key)
        counts[key] += 1
        if len(window) > k:
            old = window.popleft()
            counts[old] -= 1
            if counts[old] == 0:
                del counts[old]
        if len(window) == k:
            yield len(counts)

stream = (key for key in ["ana", "bo", "ana", "cy", "bo", "bo"])
print(list(distinct_per_window_stream(stream, 3)))
[2, 3, 3, 2]

That's the same answer as the list version you wrote earlier in this lesson. Memory is O(k), however long the stream runs.

A deque can also cap its own length. Once a capped deque is full, each append drops an item from the other end:

recent = deque(maxlen=3)
for key in ["ana", "bo", "cy", "dee"]:
    recent.append(key)
print(recent)
deque(['bo', 'cy', 'dee'], maxlen=3)

That's handy for showing the last k requests on a screen. For the Counter it's a trap: the deque drops ana without telling you, so the Counter never hears that ana left. Read window[0] before you append, or use popleft() as above.

The editor holds distinct_per_window_stream rewritten with deque(maxlen=k), and it falls into that trap. Fix it so the Counter hears about each key that leaves.

A rate limiter is a window measured in seconds

Now the rate limiter, for one client first. Keep the times of its allowed requests in a deque, oldest first. At each new request, drop from the front everything that stopped counting, then count what's left.

A request allowed at t counts while now < t + window

from collections import deque

class OneKeyLimiter:
    def __init__(self, limit, window):
        self.limit, self.window = limit, window
        # allowed requests, oldest first
        self.times = deque()

    def allow(self, now):
        while self.times and self.times[0] + self.window <= now:
            self.times.popleft()
        if len(self.times) >= self.limit:
            return False
        self.times.append(now)
        return True

limiter = OneKeyLimiter(limit=2, window=10)
for now in [0, 3, 5, 10, 12, 13, 22]:
    print(now, limiter.allow(now), list(limiter.times))
0 True [0]
3 True [0, 3]
5 False [0, 3]
10 True [3, 10]
12 False [3, 10]
13 True [10, 13]
22 True [13, 22]

Each line is now, the answer, and the times kept after the call. On a timeline, each allowed request gets a bar for the time it counts. An x is a denied request, and the last column is how many requests counted when it arrived:

Limit 2 per 10 seconds. A bar is the 10 seconds a request counts
0: allowed 0 counting before it
3: allowed 1 counting
5: denied 2 counting
10: allowed 1 counting: the one at 0 stopped at 10
12: denied 2 counting
13: allowed 1 counting
22: allowed 1 counting
051015202530
seconds

At 10 the bar from 0 has just ended, so only the request at 3 counts, and 10 gets through. At 12 the requests at 3 and 10 both count, so 12 is denied.

Write still_counting: from the times of a client's allowed requests, how many still count at now, by the rule above.

Drop a request at exactly t + window, and never store a denied one

Three details decide whether the limiter is right:

  • The drop is the rule turned around. A request counts while now < t + window, so it goes when t + window <= now. Write < there, and a request still counts at exactly 10 seconds old.
  • A denied request never goes in the deque. If it did, a client that retries faster than its limit would keep its own window full and never get through.
  • The deque stays sorted with no effort, because the times come in order. The front is always the oldest, so the while stops at the first request that still counts.

Each time is appended once and popped at most once. So a call costs O(1) amortized: averaged over all the calls, even though one call can pop many times.

The editor holds OneKeyLimiter from above with one change: allow records the request before it decides. Fix allow so a denied request is never stored.

A sliding window doesn't restart on round numbers

Take four requests at 8, 9, 10 and 11, with a limit of 2 per 10 seconds. A counter that resets every 10 seconds and the sliding log answer differently:

Request atFixed windowSliding log
8yesyes
9yesyes
10yes: a new slot starts at 10no: 8 and 9 still count
11yesno

Write fixed_window, the counter that resets on the clock, and run it on the requests at 8, 9, 10 and 11 from the table.

A deque per key, cleaned only when that key sends, never forgets a quiet client

The gateway has many clients. The first idea is a dict from each key to its own deque: the one-key limiter, once per client.

It's correct, and it never forgets anyone. A key's deque is only cleaned when that key sends again. So a client that sent one request and went quiet keeps its deque forever.

Measured with tracemalloc on 100,000 clients sending one request each, a second apart, with a 60-second window:

Memory held at the endKeys held
A deque per key84.23 MiB100,000
One shared log0.01 MiB60

Only the last 60 clients still have a request that counts.

The deque-per-key limiter keeps times_by_key, a dict from each key to a deque of its times. Write sweep, the only way that design can forget a quiet client: clean every key's deque, then delete the keys left empty.

One shared log holds only the requests that still count

The second row in that table is one deque that every key shares: a log of (time, key) pairs, oldest first. Next to it sits a dict from each key to how many of its requests still count. You'll finish this class in the editor.

Before each check, do three things for every pair at the front of the log that stopped counting:

  1. Drop it from the log.
  2. Take 1 off its key's count.
  3. Delete the key when its count reaches 0.
Predict

A shared log, 10-second window. At now = 13, which entries drop from the front?

Pick an answer above to see the rest
Part 4 done
Part 5 of 6about 8 min
The worked example

A worked example: the shortest stretch that covers every page

The prompt: a site's request log lists the page each request hit. Find the shortest stretch of consecutive requests that includes every page that appears in the log at least once. Return (start, length).

Clarify first. Say it out loud: every page means every page in this log. If several stretches tie, return the first. An empty log returns (0, 0), and a log with one page returns (0, 1).

Give the obvious answer. From every start, extend until the stretch covers every page, and keep the shortest. That's O(n²) when the answer is long, and the measurements below show it. Say it and give its cost, then improve it.

Covering every page stays true as the window grows, so shrink while it does

This window has the opposite shape. Before, a window that broke the rule stayed broken as it grew. So you shrank while it was broken, and recorded the longest.

Here, a window that covers every page still covers them all as it grows. So shrink while it's still valid, and record the shortest.

As right moves forward, the best left for it never moves back. So left only moves forward again: two indexes, O(n). The state is a Counter of the pages in the window. The window covers everything when len(counts) equals the number of different pages.

from collections import Counter

def shortest_covering_run(log):
    need = len(set(log))
    counts = Counter()
    left = 0
    best_start, best_len = 0, 0
    for right, page in enumerate(log):
        counts[page] += 1
        # covers every page: record it, then try shorter
        while len(counts) == need:
            if best_len == 0 or right - left + 1 < best_len:
                best_start, best_len = left, right - left + 1
            counts[log[left]] -= 1
            if counts[log[left]] == 0:
                del counts[log[left]]
            left += 1
    return best_start, best_len

log = ["home", "search", "home", "cart", "search", "home", "pay", "cart", "search"]
print(shortest_covering_run(log))
Predict

The log is home, search, home, cart, search, home, pay, cart, search. What's the shortest stretch that holds all 4 pages?

Pick one to see what it prints.
Pick an answer above to see the rest

Test the edges, then give the cost

Before you call the window done, run it on the inputs that break windows: an empty log, one page, and a repeat at the front.

print(shortest_covering_run([]))
print(shortest_covering_run(["home"]))
print(shortest_covering_run(["home", "home", "cart"]))
(0, 0)
(0, 1)
(1, 2)

The last one is (1, 2) because the window shrinks past the first home.

Each index enters once and leaves at most once: O(n) time, and O(m) memory for the m different pages. Here it is on logs where every request hits a different page, so the only answer is the whole log and starting over at every index does the most work:

nEvery startWindow
1,00021.5 ms0.15 ms
2,00090.2 ms0.31 ms
4,000363.9 ms0.63 ms

This is the same loop as before with its condition flipped. Shrink while broken to find the longest. Shrink while valid to find the shortest.

Write shortest_every_start, the obvious version you give first. The tests run shortest_covering_run beside it and compare the two on 500 random logs.

Part 5 done
Part 6 of 6about 28 min
Follow-ups

What interviewers ask next

What if the numbers can be negative?

The window needs the property from before: once a window breaks the rule, growing it can't fix it. Totals of numbers that are never negative have it. Totals with negative numbers don't, because a negative entry can bring an over-budget stretch back under.

Take [5, -4, 3] with a budget of 4, and shrink while the total is over budget:

Budget 4WindowTotal
right 055, over: drop the 5
right 1-4-4, length 1
right 2-4, 3-1, length 2

The whole list totals 5 - 4 + 3 = 4, length 3, and the window never looked at it.

The window drops the 5 at the first step and reports 2. But the whole list totals 4, so the answer is 3.

What replaces the window is prefix sums: running totals that start at 0. Write prefix[i] for the total of the first i values, so prefix[0] is 0, the total of no values. The values from index a to index b then total prefix[b + 1] - prefix[a]: everything up to the end of the stretch, minus everything before its start.

Predict

Prefix sums of 4, -1, 2, 1, -2, 3, 0, 2 are 0, 4, 3, 5, 6, 4, 7, 7, 9. What do the values at indexes 1 to 5 total, from the -1 to the 3?

Pick an answer above to see the rest

What about a total of at most a budget, with negative numbers?

That needs p >= total - budget, and a dict only looks up an exact value. The longest stretch ending here starts after the earliest prefix that's big enough.

Keep a running max of the prefix totals, called tops here. It never goes down, so a binary search finds the first place it reaches total - budget: check the middle of the sorted list, keep the half that can hold the answer, and repeat. Each check halves the range, so it takes about log₂ n checks, 20 for a million values. bisect_left(a, x) from Python's bisect module does it and returns the first index where a[i] >= x. The binary search lesson builds it by hand. At that point the prefix itself is big enough, and every prefix before it is too small. So the longest stretch starts right after it.

from bisect import bisect_left

def longest_within(values, budget):
    # tops[i]: the largest total of the first j values, for j <= i
    tops = [0]
    total = best = 0
    for right, v in enumerate(values):
        total += v
        # earliest prefix with p >= total - budget
        start = bisect_left(tops, total - budget)
        if start <= right:
            best = max(best, right + 1 - start)
        tops.append(max(tops[-1], total))
    return best

print(longest_within([5, -4, 3], 4))
3

Here is the last step on that list:

Values 5, -4, 3Prefix totalTop: the largest prefix so far
before index 000
after index 055
after index 115
after index 245

At index 2 the total is 4, so the stretch needs a prefix of at least 4 - 4 = 0 before it. The first top of at least 0 is before index 0, so the stretch is the whole list: length 3.

bisect_left(tops, x) from the bisect module is one binary search on a sorted list. The name isn't the point: any binary search works.

It matched checking every stretch on 5,000 random lists with negative numbers. One binary search per entry: O(n log n) time and O(n) memory.

Write the two pieces under longest_within: prefix_tops builds tops, and earliest_start is the binary search in it. The tests run longest_within on your two functions.

What's the largest value in every window?

A max can't be updated when an entry leaves. If the max is the one leaving, you don't know the next largest.

Keep a deque of indexes whose values go down from front to back. A new value first pops every smaller or equal value off the back, since those can never be the max again while it's in the window. The front is then the max, and it leaves when it falls out of the window. Say the values are requests per second:

from collections import deque

def window_max(values, k):
    # indexes; their values decrease from front to back
    best = deque()
    out = []
    for right, v in enumerate(values):
        while best and values[best[-1]] <= v:
            best.pop()
        best.append(right)
        if best[0] <= right - k:
            best.popleft()
        if right >= k - 1:
            out.append(values[best[0]])
    return out

print(window_max([3, 1, 4, 1, 5, 9, 2, 6], 3))
Predict

The largest value in each window of 3 over 3, 1, 4, 1, 5, 9, 2, 6?

Pick one to see what it prints.
Pick an answer above to see the rest

Two pointers on unsorted data: Trapping Rain Water, on compiled LeetCode lists for OpenAI and Airbnb

Trapping Rain Water is on the compiled LeetCode company lists for OpenAI and Airbnb (2 sources). Given bar heights, how much water sits between them after rain? For the heights [3, 0, 2, 0, 4, 1, 0, 2]:

Predict

Bar heights 3, 0, 2, 0, 4, 1, 0, 2. How much water sits between them after rain?

Pick an answer above to see the rest

What if the limit is too big to log every request?

The sliding log holds one timestamp per allowed request that still counts, so up to limit per key. With a limit of 1,000 a second over a 60-second window, that's 60,000 timestamps for one busy client.

When that's too much, approximate. Keep two counters per key: one for the previous fixed slot and one for the current slot. Count the previous slot in proportion to how much of it the window still covers. Say a client sent 84 requests in the previous minute and 30 so far in this one, and you're 36 seconds in:

Predict

The previous minute had 84 requests, this one has 30 so far, and you're 36 seconds in. Counting the previous minute in proportion, what's the estimate for the last 60 seconds?

Pick an answer above to see the rest

What about many gateway machines?

Each machine's own limiter lets a client through limit times on every machine. Put the counts in one shared store. Redis is the usual choice: a server that keeps keys and values in memory, which every gateway reaches over the network.

The Redis docs describe a rate limiter built on a counter. The versions on that page count each key's requests per second and let the count expire, which makes them fixed windows. INCR adds 1 to a key's count, and EXPIRE sets when the key disappears. The same page shows what two separate steps cost: if a client runs INCR but never runs EXPIRE, the key leaks until the same IP address, the client's network address, shows up again.

A check and an update in separate steps have the same problem.

Predict

Limit 10, and the shared count is 9. Two gateways each read it at the same moment, check, and add 1. How many requests get through?

Pick an answer above to see the rest

Which clock does a limiter read?

Use the time the request arrived, from a clock that never runs backwards. In Python that's time.monotonic().

The wall clock can jump when the system syncs it, and a sliding log whose times go backwards stops being sorted. Across machines the clocks disagree, so take the time in one place, such as the shared store.

What tests would you write?

  • The edge at exactly window seconds, with one test either side of it.
  • A denied request followed by one that should pass.
  • A window that crosses a round number.
  • A key twice inside the look-back window.
  • One request each from many clients, with a check that memory stays small. No correctness test finds a limiter that forgets nobody.

Turn the first test on the list above into code. Write passes_edge, which takes a limiter class such as RateLimiter, builds one limiter and checks the three calls around the edge. AllowsAll in the editor is a broken limiter that allows everything, to try your test on.

The practice problem, start to finish

That's every piece the practice problem needs. It asks for every level from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
6 questions
  1. 1.A loop moves right over n entries, and an inner while loop moves left forward to shrink the window. In total, across the whole pass, how many times can the inner loop run?

  2. 2.sizes is sorted. With lo at the first index and hi at the last, sizes[lo] + sizes[hi] is bigger than the target. Which move is safe?

  3. 3.You keep a window of the last 2 log entries in a set, adding the key that enters and removing the key that leaves. The log is ana, ana, bo. What does the set hold for the window [ana, bo]?

  4. 4.A limiter allows 2 requests per 10 seconds per client, with a sliding window. A client's requests at 8 and 9 were allowed. What happens to its request at 10?

  5. 5.You want the longest stretch whose total is at most a budget, and the numbers can be negative. Why does grow-right, shrink-left stop working?

  6. 6.A limiter keeps a dict from each client to a deque of its request times, cleaning a deque when that client sends again. After a day it has seen 10 million clients, most of whom sent one request. What's wrong, and what fixes it?

Practice

Sources (10)
  1. collections: deque objects · Python 3.12 documentation · Oct 26, 2026
    “Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.”
  2. collections: deque objects, compared with lists · Python 3.12 documentation · Oct 26, 2026
    “incur O(n) memory movement costs for pop(0) and insert(0, v) operations”
  3. collections: bounded length deques · Python 3.12 documentation · Oct 26, 2026
    “Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end.”
  4. collections: Counter objects · Python 3.12 documentation · Oct 26, 2026
    “Setting a count to zero does not remove an element from a counter.”
  5. time: time.monotonic · Python 3.12 documentation · Oct 26, 2026
    “Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards.”
  6. INCR: Pattern: rate limiter · Redis documentation · Sep 18, 2026
    “The rate limiter pattern is a special counter that is used to limit the rate at which an operation can be performed.”
  7. INCR: Pattern: rate limiter 2 · Redis documentation · Sep 18, 2026
    “If for some reason the client performs the INCR command but does not perform the EXPIRE the key will be leaked until we'll see the same IP address again.”
  8. Scripting with Lua · Redis documentation · Sep 30, 2026
    “Redis guarantees the script's atomic execution.”
  9. ZADD · Redis documentation · Sep 18, 2026
    “If a specified member is already a member of the sorted set, the score is updated and the element reinserted at the right position to ensure the correct ordering.”
  10. ZREMRANGEBYSCORE · Redis documentation · Jul 24, 2026
    “Removes all elements in the sorted set stored at key with a score between min and max (inclusive).”