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

Part 17 / 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).
fun twoSumSorted(sortedFares: IntArray, target: Int): Pair<Int, Int>? {
    var left = 0
    var right = sortedFares.size - 1
    while (left < right) {
        val sum = sortedFares[left] + sortedFares[right]
        when {
            sum == target -> return left to right
            sum < target -> left++   // too small: need a bigger left value
            else -> right--           // too big: need a smaller right value
        }
    }
    return null
}
$ kotlinc TwoPointersDemo.kt -include-runtime -d tp.jar
$ java -jar tp.jar
-- 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.kt.

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

Search the guide