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
Longest substring without repeating characters
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;
}
Two-pointer variants
ShapePointer movementExample
Opposite endslo++ or hi-- based on a comparisontwo-sum on sorted array, container with most water
Fixed-size windowboth ends move together, one step at a timemax sum of every k-length subarray
Variable-size windowright expands, left catches up when invalidlongest substring without repeats, minimum window substring
Sources
  • Crushing the Technical Interview: Data Structures and AlgorithmsTwo Pointers, Sliding Window
  • Algorithms Notes for ProfessionalsSliding Window Algorithm