Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 16 / Topic 3 of 12

Two pointers and sliding window

Two pointers means walking two indices through the same data, usually from both ends inward or one chasing the other, instead of a nested loop. A sliding window is the same idea specialised to contiguous ranges: a window of indices that grows and shrinks as you scan, re-using work instead of recomputing a sum from scratch every time. Think of two people reading a single long receipt from opposite ends toward the middle, versus one person re-reading the whole receipt from the top every time they move one line forward.

// Opposite ends, SORTED data: find two fares that add up to a target. O(n).
static int[] twoSumSorted(int[] sortedFares, int target) {
    int left = 0, right = sortedFares.length - 1;
    while (left < right) {
        int sum = sortedFares[left] + sortedFares[right];
        if (sum == target) return new int[]{left, right};
        else if (sum < target) left++;   // too small: need a bigger left value
        else right--;                     // too big: need a smaller right value
    }
    return null;
}

// Fixed-size sliding window: slide by adding the new element and dropping the oldest.
static int maxSumOfWindow(int[] dailyOrders, int windowSize) {
    int windowSum = 0;
    for (int i = 0; i < windowSize; i++) windowSum += dailyOrders[i];
    int best = windowSum;
    for (int end = windowSize; end < dailyOrders.length; end++) {
        windowSum += dailyOrders[end] - dailyOrders[end - windowSize];
        best = Math.max(best, windowSum);
    }
    return best;
}
$ javac TwoPointersDemo.java
$ java TwoPointersDemo
-- palindrome check (two pointers from both ends) --
"MALAYALAM" -> true
"BENGALURU" -> false

-- two-sum on SORTED fares, O(n) with two pointers --
fares [15, 20, 35, 40, 60], target 75 -> indices [0, 4] (15 + 60)

-- remove duplicates in place from sorted station codes --
unique count: 4, front of array: [101, 102, 104, 108]

-- max sum of any 3 consecutive days (fixed window) --
daily orders: [120, 180, 90, 240, 60, 300, 150]
best 3-day window: 600

-- shortest run of transactions totalling at least Rs 100 (variable window) --
transactions: [10, 20, 30, 15, 25, 40]
shortest window length: 4

The last example is a variable-size window: right always moves forward, but left only moves forward (shrinking the window) once the current window's sum already meets the target — the window grows to find a valid range, then shrinks to find the shortest one, all in a single forward pass with no re-scanning.

⚠️ Two pointers from both ends needs sorted data. twoSumSorted relies on "moving left right increases the sum, moving right left decreases it" — true only because the array is sorted. On unsorted data, go back to hashing (section 2) instead.

Full program: examples/two-pointers/TwoPointersDemo.java.

Done here? The practice set for Part 16 — including the solutions — is on the part page.

Search the guide