Solving the Container With Most Water Problem in Go (Two-Pointer Trick Explained)

Problem Description

The Container With Most Water problem asks: given an array of non-negative integers representing vertical line heights on the x-axis, find two lines that, together with the x-axis, can hold the most water. In other words, we want to choose two positions i and j such that the area between the vertical lines at i and j is maximized. The area of water contained by any two lines is determined by the width between them and the height of the shorter line. Formally, if we have lines at indices i and j (with i < j), the width is (j - i) and the height is min(height[i], height[j]). The water container's area is then:

Area(i,j) = (j - i) × min(height[i], height[j])

Our goal is to find i and j that maximize this area.

To make it more concrete, imagine each array value is the height of a wall on a flat surface. Pour water between any two walls, and the water will rise only as high as the shorter wall (since it would spill over the shorter side). The farther apart the walls, the more water it could potentially hold – but only if both walls are tall enough. The Container With Most Water problem is essentially asking: which two walls form the biggest "bucket" to hold water?

Intuition: Why Not Brute Force?

A straightforward approach would be to check every possible pair of lines, compute the area for each, and keep track of the maximum. While conceptually simple, this brute-force method would require examining on the order of n² pairs for n lines (about n(n-1)/2 pairs). For even moderately large arrays, that's a lot of computation – definitely not ideal.

Instead, we can solve this problem more cleverly in O(n) time by avoiding redundant comparisons. The trick is to use a two-pointer technique, which is both efficient and easy to implement. In fact, this problem is famously solved with two pointers moving towards each other, and it's a classic interview question at companies like Google, Facebook, Amazon, and more for demonstrating problem-solving skills with greedy strategies.

The Two-Pointer Trick Explained

The key insight is to use two pointers starting at the ends of the array (one at the leftmost line and one at the rightmost line). These two pointers represent our current candidate container: initially the widest possible container. We then gradually move the pointers toward each other, trying to find a better container along the way. Here's how it works:

  1. Start with the widest container: set one pointer at the beginning (index 0) and the other at the end (index n-1). This gives the maximum possible width. Compute the area = width × min(height[left], height[right]) for this pair.

  2. Move the shorter side inward: Next, compare the heights at the two pointers. If the left pointer is shorter (height[left] < height[right]), we move left one step to the right. If the right pointer is shorter or equal (height[right] <= height[left]), we move right one step to the left. By doing this, we are potentially looking for a taller line that might hold more water. Crucially, we always discard the shorter line from consideration because it limits the water height for any container using it.

  3. Check new area & repeat: After moving one pointer, compute the new area with the updated pair of lines. Update the maximum area if this new area is larger. Then repeat the process: continue moving the pointer that points to the shorter line inward, and keep checking areas, until the two pointers meet.

Why move the pointer at the shorter line? Here's an intuitive way to think about it: suppose we have two lines at positions i and j. Without loss of generality, say the line at i is shorter than the line at j. The area of this container is limited by the height at i. Now, moving the right pointer (j) inward to j-1 will decrease the width, and the height is still limited by the line at i (which hasn't changed) or possibly an even shorter line. This can only result in the same or a smaller area than before. On the other hand, if we move the left pointer (i) inward to i+1, we reduce the width slightly, but we have a chance to find a taller line that could increase the min-height part of the area formula. In essence, shifting the shorter side is the only way to find a taller line that might compensate for the loss of width. Moving the taller side wouldn't help, because the bottleneck (the shorter side) remains and the width only shrinks.

This greedy strategy ensures we explore all plausible containers without explicitly checking every pair. Only the current pair is evaluated at each step; the other pairs are ruled out by a bound, so we end up doing on the order of n comparisons/area calculations instead of n². In fact, the two-pointer approach will compute an area at most n-1 times (one for each step of the loop). That's why this solution runs in linear time O(n), which is a huge improvement over brute force. And because we only use a few variables for indices and area tracking, it uses constant extra space O(1).

The invariant is that the best area already seen, together with pairs inside the remaining interval, still contains a global optimum. If height[left] <= height[right], then for every k between them:

area(left, k) <= height[left] × (k - left)
             <= height[left] × (right - left)
             == area(left, right)

After recording the current area, no untested pair using left can improve it. Discarding left is therefore safe. The right-side argument is symmetric, and when the heights tie either endpoint can be discarded.

Let's walk through a quick example of the pointer technique in action: Suppose the heights array is [1, 5, 6, 3, 4, 2]. Initially, left = 0 (height 1) and right = 5 (height 2). The width is 5 and the limiting height is min(1, 2) = 1, so the area is 5 × 1 = 5. Here the left line is shorter, so we move the left pointer inward. Now left = 1 (height 5) and right = 5 (height still 2). The width narrowed to 4, but the limiting height is now min(5, 2) = 2, giving area 4 × 2 = 8. The area grew because we found a taller left wall. Next, the right wall is shorter (height 2 vs 5), so we move the right pointer inward. We would continue this process until the pointers meet, checking areas at each step. In the end, this method finds the maximum area without having to try every possible pair.

Implementation in Go

Inputs are non-negative heights. The function returns zero for fewer than two lines and assumes the largest possible area fits in int; use checked/wider arithmetic for inputs outside that bound.

Now that we've reasoned through the approach, let's implement it in Go. The code will use two pointers (left and right) and move them towards each other, keeping track of the largest area found:

// maxArea finds the maximum water container area for a given height array.
func maxArea(height []int) int {
    left, right := 0, len(height)-1
    maxArea := 0

    for left < right {
        // Calculate the area for the current pair of lines.
        width := right - left
        h := height[left]
        if height[right] < h {
            h = height[right]  // h = min(height[left], height[right])
        }
        area := h * width
        if area > maxArea {
            maxArea = area  // update max area if we found a bigger one
        }

        // Move the pointer at the shorter line inward to try for a taller line.
        if height[left] < height[right] {
            left++      // left side is shorter, move it right
        } else {
            right--     // right side is shorter (or equal), move it left
        }
    }

    return maxArea
}

How this code works: We initialize left at the start and right at the end of the array. In each iteration of the loop, we compute the area formed by the two lines at height[left] and height[right]. We determine the shorter of the two lines (h) to use as the height, calculate the area, and update maxArea if necessary. Then we move whichever side had the shorter line inward by one, hoping to find a taller line that might increase the area. This process continues until left and right meet. By the end, maxArea holds the largest area found.

Conclusion

The Container With Most Water problem demonstrates a classic application of the two-pointer technique to optimize a brute-force approach. The final solution is elegant in its simplicity—by greedily moving inward from the widest container and always discarding the shorter side, we efficiently find the maximum area without wasted work. In an interview or real-world scenario, recognizing this two-pointer pattern can turn a seemingly hard problem into an approachable one. Personally, I find this solution satisfying because it feels like a little mind trick: once you see why moving the smaller wall works, the problem immediately becomes easier. Hopefully, this walkthrough and code example helped demystify the problem. Happy coding!