#11

Container With Most Water

Medium
ArrayTwo PointersGreedyHash MapArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution (Two Pointers)
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The two-pointer approach is efficient because it reduces the number of comparisons by leveraging the properties of the container. By moving the pointer pointing to the shorter line, we can potentially find a taller line that may yield a larger area.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two pointers, one at the start and one at the end of the height array.
  2. 2Step 2: Calculate the area formed by the lines at the two pointers and update the maximum area if this area is larger.
  3. 3Step 3: Move the pointer that points to the shorter line inward, as this may lead to a larger area with a taller line.
solution.py15 lines
1# Full working Python code with comments
2
3def maxArea(height):
4    max_area = 0  # Initialize max area
5    left, right = 0, len(height) - 1  # Two pointers
6    while left < right:
7        # Calculate area
8        area = min(height[left], height[right]) * (right - left)
9        max_area = max(max_area, area)  # Update max area
10        # Move the pointer pointing to the shorter line
11        if height[left] < height[right]:
12            left += 1
13        else:
14            right -= 1
15    return max_area

Complexity note: The time complexity is O(n) because we only traverse the height array once with two pointers. The space complexity is O(1) since we use a constant amount of extra space.

  • 1The area of water that can be contained is determined by the shorter of the two lines and the distance between them. This means we should focus on maximizing the height and the distance.
  • 2Using two pointers allows us to efficiently explore potential containers without needing to check every pair, leading to a significant reduction in time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.