Topic 2 of 8

Two Pointers and Sliding Window for Coding Interviews

Two pointers and sliding window explained with pictures: when each works, step-by-step diagrams, a quiz and practice problems in Python and JavaScript.

  • 3 min read
  • 5-question quiz
  • 3 practice problems

Many array and string problems ask about pairs or stretches of items. Checking every pair or every stretch is O(n²). Two pointers and sliding windows get the same answer in O(n) by moving two indexes through the data in a way that never has to go back.

leftrightwalk towards each othereach step rules out a book for good
Two pointers: start at both ends and walk towards each other. Every step rules something out, so you never look at the same pair twice.

Two pointers from both ends

Start one pointer at the beginning and one at the end, and move them towards each other. At each step, a simple rule decides which pointer moves.

Typical uses:

  • Palindromes: compare s[left] with s[right], then move both inwards.
  • Pairs in a sorted array: if a[left] + a[right] is too small, move left up (to a bigger number); if it's too big, move right down.
  • Reversing in place: swap and move inwards.

Why it's correct for sorted pairs: when the sum is too small, a[left] can't be part of any answer with the remaining right-side numbers (they're all at most a[right]), so it's safe to discard it. Each step discards one item for good, so there are at most n steps.

Pair that adds up to 13, sorted input1 / 4
leftright
1
0
3
1
4
2
6
3
9
4
11
5

1 + 11 = 12: too small, so move left up to a bigger number.

Spot it

Sorted input plus "find a pair" is a big hint. Reach for two pointers before you reach for a hash map.

Two pointers in the same direction

A "slow" and a "fast" pointer both move forward. The fast one explores; the slow one marks where to write or where the current stretch starts. Removing duplicates from a sorted array in place, or moving all zeros to the end, are classic examples.

Sliding window

A window is the stretch between left and right. Move right forward one step at a time to grow the window, and move left forward to shrink it whenever the window breaks a rule.

23124351the windowslide →add on the rightdrop from the left
A sliding window: add the next item on the right, drop items from the left when the window breaks the rule.
python
1left = 0
2for right, item in enumerate(items):

right moves forward every step

3    add item to the window
4    while the window breaks the rule:

shrink only while the rule is broken

5        remove items[left] from the window
6        left += 1

left only ever moves forward too

7    the window [left, right] is now valid: update the answer

now [left, right] is a valid window

Both pointers only move forward, so the total work is O(n), even with the while inside the for.

Shortest stretch with a total of at least 71 / 4
leftright
2
0
3
1
1
2
2
3
4
4
3
5

Grow until the total reaches 7: 2 + 3 + 1 + 2 = 8. Length 4.

Window typeShrink when...Example
Longest valid windowthe window becomes invalidLongest stretch with no repeated letter
Shortest valid windowthe window is valid (to see if a smaller one is)Shortest stretch with sum ≥ target
Fixed size kthe window has more than k itemsBest total of any 7 days in a row

How to spot these problems

  • "Contiguous", "substring", "subarray", "in a row" → think sliding window.
  • "Sorted array" plus "pair" or "triplet" → think two pointers from both ends.
  • "In place", "without extra space" → think slow and fast pointers.

Common mistakes

  • Off-by-one window sizes: the window [left, right] has right - left + 1 items.
  • Updating the answer at the wrong moment: for "longest", update after shrinking; for "shortest", update inside the shrinking loop.
  • Forgetting to remove the outgoing item's count from the window's map when left moves.

Nice work!

You've got the big idea. Try the quick quiz below, then put it to work on the practice problems.

Quick quiz

5 questions. Pick an answer to see the explanation.

0/5
  1. 1In a sorted array, the pair at the two pointers adds up to less than the target. What should you do?

  2. 2A sliding window solution has a while loop inside a for loop. Why can it still be O(n)?

  3. 3Which problem is a sliding window NOT a good fit for?

  4. 4The window runs from index left to index right, inclusive. How many items does it hold?

  5. 5To check whether a string is a palindrome using two pointers, how much extra space do you need?

Practise what you learned

Solve them in your browser, in Python or JavaScript.

  1. Problem 1Palindrome check that ignores punctuationeasy
  2. Problem 2Shortest stretch of days that reaches a goalmedium
  3. Problem 3Longest playlist stretch with at most k artistsmedium