01 / 20

Two-Pointer &
Sliding Window

Master two essential array/string patterns that reduce brute-force quadratic loops down to elegant linear-time solutions in Java.

Java Algorithms

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.

Two-Pointer
Two indices traverse the data: often one from each end, or both from the start at different speeds.
Sliding Window
A contiguous range defined by a left and right bound expands or shrinks as it "slides" across the data.

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

Two-Pointer 1 3 5 7 9 left right Sliding Window 2 4 6 1 8 window size = 3 slides right Pointers converge from ends (or move at different speeds) A fixed/variable window slides across contiguous elements
\( O(n) \)
\( O(n) \)

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.

Java Pattern
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.

Java Pattern (variable window)
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

1
Identify the pattern: Are you looking at pairs (two-pointer) or contiguous ranges (sliding window)?
2
Check prerequisites: Two-pointer often needs a sorted input. Sliding window needs a clear expand/shrink condition.
3
Initialize pointers: Set left and right. Decide starting positions (same end or opposite ends).
4
Define the decision rule: What condition moves each pointer? Write the while/for loop body.
5
Track the answer: Update max/min/result inside the loop. Return after the loop ends.

Example 1: Two Sum (Sorted)

Given a sorted array and a target, find two numbers that add up to the target. Return their indices.

2 3 5 7 8 11 15 left right target = 17 2 + 15 = 17 ✓ Found!
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

1
left = 0, right = 6: sum = 2 + 15 = 17 = target. Found!
★
If the sum were too small, we'd move left++ to increase it (sorted: next value is larger).
★
If the sum were too large, we'd move right-- to decrease it.

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.

1 4 2 7 3 1 5 k = 3 sum = 4 + 2 + 7 = 13 k = 3 max = 13 slide right
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.

a b c a d b c window = "bcad" length = 4 (best so far) HashSet: {b, c, a, d}
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.

Remove Duplicates
Slow pointer marks the "write" position. Fast pointer scans ahead for new values.
Merge Sorted Arrays
One pointer per array, both advancing forward to merge elements in order.

Common Mistakes

✕ Forgetting to Sort
Two-pointer pair-sum requires sorted input. Applying it to an unsorted array gives wrong results.
✕ Off-by-One Window
Window length is \( \texttt{right} - \texttt{left} + 1 \), not \( \texttt{right} - \texttt{left} \). Missing the +1 shrinks every window by one.
✕ Not Shrinking
In variable windows, forgetting the inner 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

What is the bug in the code above?

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?