DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

LeetCode 11: Container With Most Water — Step-by-Step Visual Trace

Medium — Array | Two Pointers | Greedy

The Problem

Given an array of heights representing vertical lines, find two lines that together with the x-axis form a container that can hold the most water.

Approach

Use two pointers starting from both ends of the array. Calculate the area between the pointers and move the pointer with the smaller height inward, as moving the taller one would only decrease the area.

Time: O(n) · Space: O(1)

Code

class Solution:
    def maxArea(self, height: List[int]) -> int:
        left, right = 0, len(height) - 1
        max_area = 0

        while left < right:
            current_area = min(height[left], height[right]) * (right - left)
            max_area = max(max_area, current_area)

            if height[left] < height[right]:
                left += 1
            else:
                right -= 1

        return max_area
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

Open interactive visualization

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.

Top comments (0)