Stop 12 · Data Structures & AlgorithmsTopics · 4/11

Two Pointers & Sliding Window

Part of the Python Roadmap

In short

When a problem says "sorted array", "pair", "subarray" or "substring", two pointers or a sliding window is often the trick. Instead of checking every pair or every range, you move markers along the data once.

Two pointers move through a sorted array from both ends or at different speeds, and a sliding window keeps a range of items as it moves along. Both cut many problems from O(n²) to O(n).

The jaadu sits by an open train window, framing a passing stretch of green fields and coconut trees with both hands as the landscape slides by.

Think of it like this

The window seat on a train

Sitting at the window of a train from Mumbai to Goa, you always see a stretch of the same width. As the train moves, one new field appears on the right and one disappears on the left. You never re-look at the whole view. A sliding window keeps a running total the same way: add the new item, drop the old one.

Watch it happen

Best 3-day sales total (sliding window, k = 3)

4
0
2
1
7
2
1
3
8
4
3
5

1/5Daily sales in thousands of rupees. Find the best total over any 3 consecutive days.

The big ideas

What you need to know

Opposite ends

On a sorted list, start left at 0 and right at the end. Too small? Move left up. Too big? Move right down.

Fast and slow

Two pointers moving at different speeds remove duplicates in place or find a linked list's middle.

Fixed window

For "best k in a row", add the incoming item and subtract the outgoing one. Each step is O(1).

Variable window

Grow the right edge, and shrink the left edge while the window breaks a rule, like "no repeated characters".

See it in code

Walk through the code

python
1def pair_with_sum(sorted_prices: list[int], target: int) -> tuple[int, int] | None:2    left, right = 0, len(sorted_prices) - 13    while left < right:4        total = sorted_prices[left] + sorted_prices[right]5        if total == target:6            return left, right7        if total < target:8            left += 19        else:10            right -= 111    return None12 13 14def best_k_day_sales(sales: list[int], k: int) -> int:15    window = sum(sales[:k])16    best = window17    for i in range(k, len(sales)):18        window += sales[i] - sales[i - k]19        best = max(best, window)20    return best21 22 23def longest_unique_substring(s: str) -> int:24    last_seen: dict[str, int] = {}25    start = best = 026    for i, ch in enumerate(s):27        if ch in last_seen and last_seen[ch] >= start:28            start = last_seen[ch] + 129        last_seen[ch] = i30        best = max(best, i - start + 1)31    return best32 33 34print(pair_with_sum([90, 150, 230, 320, 410], 500))  # (0, 4)35print(best_k_day_sales([4, 2, 7, 1, 8, 3], 3))         # 1636print(longest_unique_substring("abcabcbb"))           # 3

1/4Pointers at both ends of a sorted list. The sum tells us which one to move.

All three run in O(n) time. Brute force would check every pair or every substring.

Save yourself the pain

Common mistakes

Oops

Using opposite-end pointers on an unsorted list.

Do this instead

The move-left-or-right logic only works when the list is sorted. Sort first, or use a dict instead.

Oops

Recomputing sum(sales[i:i+k]) for every window.

Do this instead

That's O(n × k). Update the running total with one addition and one subtraction.

Oops

Off-by-one window lengths.

Do this instead

A window from start to i inclusive has length i - start + 1. Check it on a tiny example.

Your mission

Pointer practice

~30 min

Quick check

In pair_with_sum on a sorted list, the current sum is less than the target. Which pointer should move?

Go deeper

  1. 1Check if a string is a palindrome with two pointers.
  2. 2Find the longest substring without repeating characters with a sliding window.
  3. 3Find the maximum sum of k consecutive elements.

Also part of these roadmaps

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge