Coding Interview Patterns
Two Pointers & Sliding Window
Two indices walking across an array or string — from opposite ends, or as a window that grows and shrinks — turn a large class of O(n²) brute-force scans into O(n).
- Opposite-direction pointers on sorted data: two-sum on a sorted array, container-with-most-water
- Same-direction pointers as a sliding window: longest substring without repeating characters, smallest subarray with a given sum
- The window expands to explore and shrinks to restore a violated invariant — it never restarts from scratch, which is exactly what makes it O(n) instead of O(n²)
- Recognize the shape: "contiguous subarray/substring satisfying some condition" is the sliding-window tell
- Opposite-end two pointers usually require sorted input first — sorting costs O(n log n), which then dominates the two-pointer O(n) scan
static int lengthOfLongestSubstring(String s) {
Map<Character, Integer> lastSeen = new HashMap<>();
int longest = 0, windowStart = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (lastSeen.containsKey(c) && lastSeen.get(c) >= windowStart) {
windowStart = lastSeen.get(c) + 1; // jump the window start past the duplicate
}
lastSeen.put(c, i);
longest = Math.max(longest, i - windowStart + 1);
}
return longest;
}| Shape | Pointer movement | Example |
|---|---|---|
| Opposite ends | lo++ or hi-- based on a comparison | two-sum on sorted array, container with most water |
| Fixed-size window | both ends move together, one step at a time | max sum of every k-length subarray |
| Variable-size window | right expands, left catches up when invalid | longest substring without repeats, minimum window substring |