NeetCode 150, stage 2: Two Pointers

← Arrays and Hashing · All 150 problems · Sliding Window →

Two pointers replace a nested loop when the input has an order. This stage trains one decision: which pointer moves, and why that move is safe. Each move drops candidates that cannot be the answer, so one pass is enough.

Garden notes: the Go syntax for this stage, Two Pointers pattern.

Problems on this page

#ProblemLevelPatternTemplate
1125. Valid PalindromeEasyConverging pointersA: Converging pointers
2167. Two Sum II - Input Array Is SortedMediumConverging pointersA: Converging pointers
315. 3SumMediumSort, then converging pointersB: Sort, fix one, converge
411. Container With Most WaterMediumConverging pointersA: Converging pointers
542. Trapping Rain WaterHardTwo pointers with running maximumsC: Two pointers with a running maximum

Templates to memorize

Template A: Converging pointers

Signal

The slice is sorted, or the problem compares the two ends: a pair with a sum, a palindrome, the widest container. A brute-force answer tries each pair.

// TEMPLATE A: converging pointers on a sorted slice.
// Each step drops one item that cannot be in the answer.
func pairWithSum(sorted []int, target int) (int, int) {
    left, right := 0, len(sorted)-1 // 1. START at the two ends
    for left < right {              // stop before the pointers meet
        sum := sorted[left] + sorted[right] // 2. COMPARE
        switch {
        case sum == target:
            return left, right
        case sum < target:
            left++ // 3. MOVE: too small, only a larger left value can help
        default:
            right-- // too large, only a smaller right value can help
        }
    }
    return -1, -1 // no pair
}

The moves are START AT THE ENDS, COMPARE, then MOVE ONE SIDE. Move the side that cannot be part of a better answer. The loop condition is left < right, so one item is never its own partner.

Say it

“The slice is sorted, so I put a pointer at each end. A sum that is too small moves the left pointer, a sum that is too large moves the right one, so it is O(n) time and O(1) space.”

Template B: Sort, fix one, converge

Signal

The problem asks for three values that reach a target sum, with no duplicate result. The answer contains values, not indexes, so you can sort the input.

// TEMPLATE B: sort, fix one value, then converge on the items after it.
func tripletsWithSum(nums []int, target int) [][]int {
    sort.Ints(nums) // 1. SORT: equal values are now neighbors
    res := [][]int{}
    for i := 0; i < len(nums)-2; i++ { // 2. FIX nums[i] as the first value
        if i > 0 && nums[i] == nums[i-1] {
            continue // 4. SKIP: this first value already gave its triplets
        }
        left, right := i+1, len(nums)-1
        for left < right { // 3. CONVERGE, as in Template A
            sum := nums[i] + nums[left] + nums[right]
            switch {
            case sum < target:
                left++
            case sum > target:
                right--
            default:
                res = append(res, []int{nums[i], nums[left], nums[right]})
                left++
                right--
                for left < right && nums[left] == nums[left-1] {
                    left++ // 4. SKIP an equal second value
                }
            }
        }
    }
    return res
}

The moves are SORT, FIX, CONVERGE, then SKIP. The sort costs O(n log n), and the two loops cost O(n²). Skip a value only after its first use. The test i > 0 && nums[i] == nums[i-1] does that, and it keeps results such as [-1, -1, 2].

Say it

“I sort, then I fix one value and run two pointers on the rest, which is O(n²). Equal values are neighbors after the sort, so I skip them to avoid duplicates.”

Template C: Two pointers with a running maximum

Signal

The answer at each index depends on the highest value on its left and the highest value on its right. Trapped water is the model problem.

// TEMPLATE C: two pointers with a running maximum on each side.
// The lower side is safe to settle: the other side has a wall at least as
// high.
func trappedWater(height []int) int {
    left, right := 0, len(height)-1
    leftMax, rightMax := 0, 0 // highest wall seen from each end
    water := 0
    for left < right {
        // 1. COMPARE the ends: the left side is lower
        if height[left] < height[right] {
            // 2. UPDATE the maximum of that side
            leftMax = max(leftMax, height[left])
            // 3. ADD the water above this index
            water += leftMax - height[left]
            left++ // 4. MOVE that side
        } else {
            rightMax = max(rightMax, height[right])
            water += rightMax - height[right]
            right--
        }
    }
    return water
}

The moves are COMPARE THE ENDS, UPDATE THE MAXIMUM, ADD, then MOVE. All four moves apply to the lower side. That side is safe to settle, because the other side has a wall that is at least as high. Update the maximum before you add, so the result is never negative.

Say it

“The water above a bar is the lower of the two highest walls around it, minus the bar. I always move the lower side, because its own running maximum decides the water there, so it is one pass and O(1) space.”

Mistakes in this stage

  • for left <= right in a pair problem compares one item with itself. Use left < right.
  • sort.Ints sorts in place and changes the caller’s slice. If the problem needs the original indexes, do not sort.
  • s[i] is a byte, not a character. For text that is not ASCII, convert the string to []rune first.
  • len(nums)-1 is -1 for an empty slice. The condition left < right then stops the loop before a read.

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

125. Valid Palindrome

LeetCode 125 · Easy

167. Two Sum II - Input Array Is Sorted

LeetCode 167 · Medium

15. 3Sum

LeetCode 15 · Medium

11. Container With Most Water

LeetCode 11 · Medium

42. Trapping Rain Water

LeetCode 42 · Hard


← Arrays and Hashing · All 150 problems · Sliding Window →