Topic 10 of 21 · Intermediate
Two Pointers & Sliding Window
Turn O(n²) subarray/substring scans into O(n) by moving two indices smartly.
Concept
Two pointers: keep one index at each end (or both at the start) and move whichever pointer brings you closer to the answer. Works great on sorted arrays.
Sliding window: keep a window [left, right] that satisfies a condition. Grow right every step; shrink left while the window is invalid. Each element enters and leaves once, so total work is O(n).
Fixed-size windows (size k) just slide by one; variable windows expand and shrink based on a rule such as 'no repeated characters' or 'sum ≤ target'.
Complexity
| Operation | Time | Space |
|---|---|---|
| Pair sum in sorted array | O(n) | O(1) |
| Longest substring without repeats | O(n) | O(k) |
| Max sum of window size k | O(n) | O(1) |
Code (Python)
def longest_unique_substring(s):
last = {}
left = best = 0
for right, ch in enumerate(s):
if ch in last and last[ch] >= left:
left = last[ch] + 1 # shrink past the duplicate
last[ch] = right
best = max(best, right - left + 1)
return best
def min_subarray_len(target, nums):
left = total = 0
best = float("inf")
for right, x in enumerate(nums):
total += x
while total >= target: # window valid -> try shrinking
best = min(best, right - left + 1)
total -= nums[left]
left += 1
return 0 if best == float("inf") else bestRemember
- Ask: 'contiguous subarray/substring?' → think sliding window.
- Sorted input + pair/triplet → think two pointers.
- Each pointer only moves forward, which is why it's linear.
Practice these interview problems
- 3Sum
- Container With Most Water
- Minimum Window Substring
- Longest Repeating Character Replacement
Lesson test
Take an 8-question test on “Two Pointers & Sliding Window” — concepts, output prediction, bug spotting and interview questions.