An interactive visualization of how the two-pointer technique finds the maximum area container. Watch the algorithm converge from both ends to find the optimal pair of lines.
Two Pointers LeetCode 11 โ Mediumheight of length n. There are n vertical lines drawn such that the two endpoints of the i-th line are (i, 0) and (i, height[i]).left and right is: area = (right - left) * min(height[left], height[right]).
fun maxArea(height: IntArray): Int { var left = 0; var right = height.size - 1 var maxArea = 0 while (left < right) { val w = right - left val h = minOf(height[left], height[right]) val area = w * h maxArea = maxOf(maxArea, area) if (height[left] < height[right]) left++ else right-- } return maxArea}
The area between two lines is determined by the shorter line and the distance between them:
area = width * min(height[left], height[right]). Starting with the widest container (pointers at both ends),
we can only potentially increase the area by moving the shorter side inward โ moving the taller side would
only decrease the width while the height is still limited by the shorter side.
left at the start (index 0) and right at the end (index n-1)left and rightmax_area, update itheight[left] < height[right], move left right (increment); otherwise move right left (decrement)max_areaIf we move the taller side inward, the width decreases by 1 and the height can only stay the same or decrease (since it's bounded by the shorter side). So the area would definitely not increase. By moving the shorter side, we have a chance of finding a taller line that could increase the area despite the reduced width.
Each pointer moves at most n - 1 steps total, and each step does constant work. We use only a fixed number of variables.