Taro Logo

Container With Most Water

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+41
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2.1K views
Topics:
ArraysTwo PointersGreedy Algorithms

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example 2:

Input: height = [1,1]
Output: 1

Constraints:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the input array has fewer than two elements?
  2. Are all the values in the height array guaranteed to be non-negative integers?
  3. Can the width of the container be calculated simply by the difference in the indices of the two lines?
  4. If there are multiple pairs that yield the same maximum water amount, does it matter which one's capacity we return?
  5. Should we handle cases where the input array is null or empty, and what should be returned in such cases?

Brute Force Solution

Approach

Imagine you have a row of vertical walls of different heights and you want to pick any two walls to form a container that holds the most water. The brute force approach involves trying every single possible pair of walls, measuring how much water each pair can hold, and keeping track of the largest amount found.

Here's how the algorithm would work step-by-step:

  1. Begin by selecting the very first wall on the far left as the first side of your container.
  2. Pair this first wall with every other wall to its right, one by one.
  3. For each pair, calculate how much water the container can hold based on the distance between the two walls and the height of the shorter wall.
  4. Remember the amount of water held if it is greater than any previous amount you have checked.
  5. Once you have paired the first wall with every other wall, move to the second wall in line.
  6. Pair this second wall with every wall to its right, calculating the water capacity for each combination and updating your largest amount.
  7. Repeat this process for every possible wall, systematically testing every combination of two walls.
  8. After you have checked every single pair, the largest amount of water you recorded is your final answer.

Code Implementation

def max_area(heights):    maximum_water = 0    total_walls = len(heights)    # Evaluate every possible pair of walls to find the maximum possible container volume    for left_index in range(total_walls):        for right_index in range(left_index + 1, total_walls):            distance_between = right_index - left_index            shorter_height = min(heights[left_index], heights[right_index])            current_water = distance_between * shorter_height            # Track the peak water capacity found across all evaluated wall pairings            if current_water > maximum_water:                maximum_water = current_water    return maximum_water

Big(O) Analysis

Time Complexity
O(n²) – To analyze the time complexity, let n represent the number of walls in the input array. The algorithm systematically pairs each wall with every other wall to its right using nested iterations. For the first wall, we compute the water capacity with the remaining n-1 walls, for the second wall we check n-2 walls, and so on until the final wall. Summing these comparisons yields approximately n * n/2 total operations, which simplifies in asymptotic analysis to a time complexity of O(n²).
Space Complexity
O(1) – The brute force approach described relies entirely on a few primitive scalar variables, such as loop counters and a running maximum, to keep track of the current pair and the largest amount of water recorded. No additional data structures, such as temporary lists or hash maps, are allocated regardless of the input size N. Therefore, the extra memory required remains constant and does not scale with the number of walls.

Optimal Solution

Approach

Instead of checking every single combination of walls to find the biggest area, the optimal approach uses a clever narrowing strategy from the outer edges inward. By starting with the widest possible container and smartly moving our boundaries based on height, we can quickly find the maximum possible water capacity.

Here's how the algorithm would work step-by-step:

  1. Imagine placing one marker at the very beginning of the row of walls and another marker at the very end to create the widest possible container.
  2. Measure the amount of water this outer container can hold, keeping in mind that the water level is limited by whichever of the two boundary walls is shorter.
  3. Compare this current container's capacity to the largest amount of water you have seen so far, and update your record if the current one is bigger.
  4. Look at the two walls forming the current container and identify the shorter one.
  5. Move the marker of the shorter wall one step inward toward the middle, because keeping that short wall will never allow you to hold more water even if you find a taller wall on the other side.
  6. Leave the taller wall marker right where it is, since it still has a chance to form an even bigger container with a different partner.
  7. Repeat this process of measuring, comparing, and moving the shorter wall inward until the two markers finally meet in the middle.

Code Implementation

def max_area(height_list):
    left_marker = 0
    right_marker = len(height_list) - 1
    max_water_seen = 0

    while left_marker < right_marker:
        # Width decreases, so we must greedily move the shorter wall to seek a taller replacement.
        width_between = right_marker - left_marker
        
        height_left = height_list[left_marker]
        height_right = height_list[right_marker]
        limiting_height = min(height_left, height_right)
        current_capacity = width_between * limiting_height

        # Track the absolute maximum capacity found across all pointer positions.
        if current_capacity > max_water_seen:
            max_water_seen = current_capacity

        # The shorter wall limits capacity; keeping it can never yield a larger area with new widths.
        if height_left < height_right:
            left_marker += 1
        else:
            right_marker -= 1

    return max_water_seen

Big(O) Analysis

Time Complexity
O(n) – We use a two-pointer approach starting at both ends of the array with size n and move them inward step by step until they meet in the middle. In each iteration, exactly one pointer moves inward, meaning each element is visited at most once. This linear traversal of the input array requires approximately n operations in the worst case, which simplifies to O(n).
Space Complexity
O(1) – The algorithm relies solely on a few scalar variables such as left and right markers, the current area, and the maximum water capacity seen so far. These variables require a constant amount of extra memory regardless of the input size. No auxiliary data structures, temporary lists, or recursive call stacks are utilized during the process. Therefore, the auxiliary space complexity remains constant at O(1) as N scales.

Edge Cases

Array with fewer than two elements
How to Handle:
Return zero immediately since a container requires at least two vertical lines.
Array with exactly two elements
How to Handle:
Calculate the area for the single possible pair and return that value as the maximum.
Heights containing zeros
How to Handle:
The two-pointer approach naturally moves past zeros because the minimum height formula results in zero area, driving the pointer inward.
Array with all identical height values
How to Handle:
The initial outer pointers calculate the maximum possible width container, and subsequent pointer movements safely evaluate smaller widths.
Highly skewed distributions such as tall walls on the outside and short walls in the middle
How to Handle:
The greedy two-pointer strategy ensures we always discard the shorter line, guaranteeing we do not miss the optimal container.
Extremely large inputs with maximum constraint sizes
How to Handle:
An O(n) linear scan using two pointers processes millions of elements efficiently within time limits without exceeding memory or recursion limits.
Maximum possible integer values for heights and maximum array length
How to Handle:
Use 64-bit integers for the area calculation to prevent potential integer overflow when multiplying maximum width by maximum height.
0/75 completed