Two pointers & sliding window
Recognise and apply window and pointer patterns.
By Invicly Tech, , in Interview Preparation. About 11 minutes to read.
In short
Two pointers walk an array from both ends or at different speeds, avoiding nested loops. A sliding window is a pair of pointers marking a range that grows and shrinks as you scan.
Explained simply
Two pointers means using two index variables instead of one to walk through the data. Rather than checking every pair of positions with two nested loops, the pointers move in a smart way, so each step rules out many pairs at once. The result is usually O(n) instead of O(n squared).
Picture two people searching a sorted bookshelf for two books whose prices add to 50. One starts at the cheap end, one at the expensive end. If the total is too high, the person at the expensive end steps left. Too low, the cheap end steps right. They never need to check every pair.
A sliding window is two pointers that mark the start and end of a block of neighbouring items. You push the end forward to grab more, and pull the start forward when the block breaks a rule, like "no repeated letters". It moves along the array like a caterpillar.
The key question is whether the answer is a contiguous block (use a window) or a pair chosen from anywhere in sorted data (use opposite ends). Once you spot which, the code follows a template you can reuse.
Press Play on a diagram to walk through it one step at a time.
- 1Expand right
Add s[right] to the window state
- 2Check validity
Does the window break the rule?
- 3Shrink left
While invalid, remove s[left] and move left
- 4Update best
Record window size or sum
- 5Repeat to end
Each index enters and leaves once: O(n)
- left = 0, right = n - 1
- Sorted input or palindromes
- Move the pointer that can improve
- 3Sum, Container With Most Water
- Both start at 0
- Contiguous subarray or substring
- Grow right, shrink left
- Longest Substring Without Repeats
- Step 11 + 11 = 12
Too big: move right pointer left
- Step 21 + 7 = 8
Too small: move left pointer right
- Step 32 + 7 = 9
Found after 3 checks instead of 15 pairs
- Expand right every step
- Shrink only while invalid
- Record after shrinking
- Longest Substring Without Repeats
- Expand right until valid
- Shrink while still valid
- Record inside the shrink loop
- Minimum Window Substring
In depth
Why moving one pointer is safe
With sorted numbers and pointers at both ends, suppose nums[left] + nums[right] is bigger than the target. Pairing nums[right] with anything to the right of left gives an even bigger sum, because those values are larger. So nums[right] can never be part of an answer, and moving right inward throws away only useless pairs.
The same "throw away a whole row of pairs" argument proves Container With Most Water and Two Sum II. Saying this reasoning out loud shows the interviewer you understand why the algorithm is correct, not just that it passes tests.
Fixed windows
When the window size k is given, you never shrink based on a rule. Add the new right element, remove the element that just fell off the left (index right - k), and record the answer once the window is full.
This turns "the sum or average of every block of k" from O(n × k) into O(n). The same shape solves "find all anagrams of p inside s": keep letter counts for the current k characters and compare them with the counts of p.
- Add nums[right]
- If right >= k, remove nums[right - k]
- If right >= k - 1, record the answer
- Step 1First window
2 + 1 + 5 = 8
- Step 2Slide once
Add 1, drop 2: 7
- Step 3Slide again
Add 3, drop 1: 9
- Step 4Answer: 9
O(n), not O(n x k)
Shortest window: shrink while valid
Some windows look for the shortest block that satisfies a rule, such as Minimum Window Substring (the smallest part of s containing all letters of t). The loop flips: expand right until the window is valid, then shrink left as far as possible while it stays valid, recording the size each time.
Track how many required characters are still missing in one counter, so the validity check is O(1) instead of comparing two count maps on every step. Total time is O(n + m) because each pointer only moves forward.
Counting subarrays with the at-most trick
"Count subarrays with exactly k distinct values" is awkward with one window, because shrinking can break exactness. Instead, write atMost(k), which is easy: for each right, shrink until the window has at most k distinct values. Every subarray ending at right and starting between left and right is then valid, so add right - left + 1.
Finally, exactly(k) = atMost(k) - atMost(k - 1). The same trick solves Binary Subarrays With Sum and Count Number of Nice Subarrays in O(n).
- 1Write atMost(k)
Easy with one window
- 2Grow right
Add nums[right]
- 3Shrink left
Until at most k distinct values
- 4Count
Add right - left + 1
- 5Subtract
exactly(k) = atMost(k) - atMost(k - 1)
Learn it in 5 short steps
About 1h 10m each. Track them with a timer in your plan.
- 1Learn the opposite-ends pointer pattern~1h 10m
- 2Learn fixed and variable sliding windows~1h 10m
- 3Practice: Valid Palindrome, 3Sum~1h 10m
- 4Practice: Container With Most Water~1h 10m
- 5Practice: Longest Substring Without Repeating Characters~1h 10m
Key points
- Sliding window works for contiguous ranges; each element is added and removed at most once.
- Opposite-end pointers usually need sorted input or a symmetric check.
- 3Sum is sort plus a two-pointer scan per element: O(n squared) overall.
- Phrases like longest substring or subarray with sum hint at a window.
Key terms
Tap a card to flip it. 0/4 known
Examples
def longest_unique(s):
seen = set()
left = best = 0
for right, ch in enumerate(s):
while ch in seen: # window invalid: shrink
seen.remove(s[left])
left += 1
seen.add(ch) # expand
best = max(best, right - left + 1)
return best # O(n) timeMaximum average of 4 consecutive numbers
nums = [1, 12, -5, -6, 50, 3], k = 4. The first window sums to 1 + 12 - 5 - 6 = 2. Slide: add 50, remove 1, sum = 51. Slide: add 3, remove 12, sum = 42. The best sum is 51, so the best average is 51 / 4 = 12.75. Each slide is two operations instead of re-adding k numbers: O(n) time, O(1) space.
double findMaxAverage(int[] nums, int k) {
int sum = 0;
for (int i = 0; i < k; i++) sum += nums[i];
int best = sum;
for (int r = k; r < nums.length; r++) {
sum += nums[r] - nums[r - k];
best = Math.max(best, sum);
}
return best / (double) k;
}3Sum without duplicate triplets
Sort [-1, 0, 1, 2, -1, -4] into [-4, -1, -1, 0, 1, 2]. Fix -4: no pair reaches 4. Fix the first -1: pointers find pairs summing to 1, namely (-1, 2) and (0, 1). The next -1 equals the previous fixed value, so skip it to avoid repeats. After each found pair, move both pointers and skip equal neighbours. Result [[-1, -1, 2], [-1, 0, 1]]. Time O(n squared), extra space O(1) apart from sorting and output.
List<List<Integer>> threeSum(int[] a) {
Arrays.sort(a);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < a.length - 2; i++) {
if (i > 0 && a[i] == a[i - 1]) continue;
int l = i + 1, r = a.length - 1;
while (l < r) {
int s = a[i] + a[l] + a[r];
if (s < 0) l++;
else if (s > 0) r--;
else { res.add(List.of(a[i], a[l], a[r])); l++; r--;
while (l < r && a[l] == a[l - 1]) l++; }
}
}
return res;
}Quick reference
- Sorted data + pair with a target: opposite-end pointers, O(n)
- Contiguous block + a rule: sliding window, O(n)
- Fixed window: add index right, remove index right - k
- Longest valid: shrink while invalid, then record
- Shortest valid: record and shrink while still valid
- Exactly k = atMost(k) - atMost(k - 1)
- Sum targets with negative numbers need prefix sums, not a window
Common mistakes
- Using a window on non-contiguous problems, where it does not apply.
- Forgetting to update state when shrinking the window.
- Skipping duplicate handling in 3Sum, producing repeated triplets.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Valid Palindrome: ignoring case and non-alphanumeric characters, check whether a string reads the same both ways, with O(1) extra space.
- Exercise 2medium
Longest Repeating Character Replacement: s has uppercase letters and you may change up to k of them. Find the longest substring that can become one repeated letter.
- Exercise 3hard
Minimum Window Substring: return the smallest substring of s that contains every character of t, including repeats, or "" if none exists.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How do I know a problem needs a sliding window?
- Look for words like substring, subarray, contiguous or "longest/shortest block" together with a rule you can update as items enter and leave. If the chosen items do not have to be next to each other, a window is probably wrong.
- Do I always have to sort before using two pointers?
- For opposite-end pair problems, yes, because the logic depends on sorted order. Sliding windows and fast/slow pointers do not need sorting.
- Is the nested while loop inside a window really O(n)?
- Yes. The left pointer only moves forward and can move at most n times across the whole run, so the inner loop's total work is O(n).