Two-Pointer &
Sliding Window
Master two essential array/string patterns that reduce brute-force quadratic loops down to elegant linear-time solutions in Java.
What Are These Patterns?
Both the two-pointer technique and the sliding window technique work by maintaining references (indices) into an array or string. Instead of checking every possible pair or subarray with nested loops, they move these references intelligently to explore the solution space in a single pass.
Why Do They Matter?
Many array and string problems have a naive solution that runs in \( O(n^2) \) or even \( O(n^3) \) time. By recognizing the right pattern, you can often reduce this to \( O(n) \): a massive speedup that turns time-limit failures into accepted solutions.
Visual Intuition
The Two-Pointer Rule
Place two indices into a sorted (or structurally ordered) collection. At each step, compare the elements at both pointers and advance one pointer toward the solution based on a decision rule. The loop ends when the pointers meet or cross.
int left = 0, right = arr.length - 1; while (left < right) { int sum = arr[left] + arr[right]; if (sum == target) return true; else if (sum < target) left++; else right--; }
The Sliding Window Rule
Maintain a contiguous subarray bounded by indices left and right. Expand right to include more elements; shrink by advancing left when a constraint is violated. Track an aggregate (sum, count, set) as the window changes.
int left = 0, windowSum = 0; for (int right = 0; right < arr.length; right++) { windowSum += arr[right]; while (windowSum > target) { windowSum -= arr[left++]; } best = Math.max(best, right - left + 1); }
Two-Pointer vs Sliding Window
| Two-Pointer | Sliding Window | |
|---|---|---|
| Data requirement | Often sorted | Any order |
| Pointer start | Both ends (or same end) | Same end (left, right) |
| Movement | Towards each other | Both move right |
| Subarray? | Not necessarily | Always contiguous |
| Typical problems | Pair sums, palindromes | Max/min subarray, unique chars |
| Time complexity | \( O(n) \) | \( O(n) \) |
How to Apply the Pattern
Example 1: Two Sum (Sorted)
Given a sorted array and a target, find two numbers that add up to the target. Return their indices.
int left = 0, right = nums.length - 1; while (left < right) { int sum = nums[left] + nums[right]; if (sum == target) return new int[]{left, right}; else if (sum < target) left++; else right--; } return new int[]{-1, -1}; // not found
Walkthrough: Two Sum Logic
Example 2: Max Sum of Size \( k \)
Find the maximum sum of any contiguous subarray of exactly size \( k \). This is the classic fixed-size sliding window.
int windowSum = 0, maxSum = 0; for (int i = 0; i < k; i++) windowSum += arr[i]; // first window maxSum = windowSum; for (int i = k; i < arr.length; i++) { windowSum += arr[i] - arr[i - k]; // slide maxSum = Math.max(maxSum, windowSum); }
Example 3: Longest Unique Substring
Find the length of the longest substring without repeating characters. This uses a variable-size sliding window with a HashSet.
Set<Character> seen = new HashSet<>(); int left = 0, maxLen = 0; for (int right = 0; right < s.length(); right++) { while (seen.contains(s.charAt(right))) seen.remove(s.charAt(left++)); seen.add(s.charAt(right)); maxLen = Math.max(maxLen, right - left + 1); }
Same-Direction Two Pointers
Not all two-pointer problems start from opposite ends. Sometimes both pointers begin at index 0 and move right at different speeds: a slow pointer and a fast pointer.
Common Mistakes
while to shrink left causes the window to only grow, missing valid shorter windows.Pattern Summary
| Problem Clue | Pattern | Technique |
|---|---|---|
| Pair with target sum | Two-Pointer (opposite ends) | Sort + converge |
| Remove duplicates in-place | Two-Pointer (same direction) | Slow/fast pointers |
| Max sum of size \( k \) | Fixed Sliding Window | Add right, subtract left |
| Longest substring (unique) | Variable Sliding Window | Expand right, shrink left |
| Smallest subarray \( \ge \) target | Variable Sliding Window | Shrink when valid |
| Palindrome check | Two-Pointer (opposite ends) | Compare & converge |
Question 1 of 5
What is the time complexity of the two-pointer technique for finding a pair that sums to a target in a sorted array of \( n \) elements?
Question 2 of 5
In a fixed-size sliding window of size \( k \), how do you compute the sum of the next window position?
Question 3 of 5
Which data structure is commonly used alongside a variable-size sliding window to find the longest substring without repeating characters?
Question 4 of 5
Consider this code:
int left = 0, right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) return true;
else if (sum < target) right--;
else left++;
}
The array nums is sorted in ascending order.
What is the bug in the code above?
left++ (to a bigger value). When \( \texttt{sum} > \texttt{target} \), we need a smaller sum, so we move right--. The code does the opposite, which is the bug.Question 5 of 5
You need to find the smallest contiguous subarray whose sum is greater than or equal to a target. Which pattern should you use?