Largest Tank Area Between Vertical Walls

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

You are given a list heights of n non-negative integers where heights[i] denotes the height of a thin vertical wall standing at horizontal coordinate i. Picking any two distinct walls at coordinates left and right (0 <= left < right < n) together with the flat ground (y = 0) creates an upright rectangular water tank.

Because water overflows above the shorter of the two chosen walls and the tank cannot be tilted, the cross-sectional water area held between left and right is:

(right - left) * min(heights[left], heights[right])

Intermediate walls between left and right have zero width and neither block nor displace water. Return the largest water area achievable by any pair of walls.

def max_area(heights: List[int]) -> int:

Examples

Example 1

  • Input: heights = [2, 9, 4, 1, 6, 9, 3, 8]
  • Output: 48
  • Walk-through: Selecting the wall at index 1 (height 9) and the wall at index 7 (height 8) yields width 7 - 1 = 6 and water height min(9, 8) = 8, producing area 6 * 8 = 48. Pairing the two height-9 walls at indices 1 and 5 gives a taller water level (9) but narrower width (5 - 1 = 4), reaching only 36.

Example 2

  • Input: heights = [4, 6]
  • Output: 4
  • Walk-through: Only one pair (0, 1) exists, with width 1 - 0 = 1 and water height min(4, 6) = 4, for an area of 1 * 4 = 4.

Constraints

  • 2 <= len(heights) <= 10^5
  • 0 <= heights[i] <= 10^4

Step-by-step walkthrough

  1. Understand the geometry of a tank

    Picking any two vertical walls at positions left < right forms an upright rectangle with y = 0:

    • Width: horizontal span right - left.
    • Height: min(heights[left], heights[right]), since water overflows above whichever wall is shorter.
    • Interior walls: ignored — walls have zero thickness and do not block or displace water.
    Example 1: heights = [2, 9, 4, 1, 6, 9, 3, 8]
    
      9 |     |               |
      8 |     |~~~~~~~~~~~~~~~|~~~~~~~|   <-- water level = min(9, 8) = 8
      7 |     |               |       |
      6 |     |           |   |       |
      5 |     |           |   |       |
      4 |     |   |       |   |       |
      3 |     |   |       |   |   |   |
      2 | |   |   |       |   |   |   |
      1 | |   |   |   |   |   |   |   |
        +-------------------------------
          0   1   2   3   4   5   6   7
              ^                       ^
           left = 1               right = 7
           area = (7 - 1) * min(9, 8) = 6 * 8 = 48
    

    We want the largest area across all pairs 0 <= left < right < n, where n can reach 10^5.

  2. Why checking all pairs is too slow

    A direct nested loop evaluates every (i, j) pair and remembers the maximum:

    def max_area_brute(heights):
        best_area = 0
        for i in range(len(heights)):
            for j in range(i + 1, len(heights)):
                area = (j - i) * min(heights[i], heights[j])
                if area > best_area:
                    best_area = area
        return best_area
    

    At n = 10^5, there are n * (n - 1) / 2 — nearly 5 * 10^9 — pairs (O(n^2) time), which is far too slow. Reaching O(n) time requires discarding an entire family of inferior pairs on every step.

  3. Key insight: start widest and discard the shorter wall

    Start with two pointers at the far ends: left = 0 and right = len(heights) - 1, giving the maximum possible width (n - 1). After recording (left, right), which wall should step inward?

    Suppose heights[left] <= heights[right], and compare (left, right) against any narrower partner r' (left < r' < right) paired with left:

    1. Strictly smaller width: r' - left < right - left.
    2. Water height still capped by left: min(heights[left], heights[r']) <= heights[left], regardless of how tall heights[r'] is!
    Suppose heights[left] = 2 and heights[right] = 8:
    
      left = 0 (h=2)          r' (even if h=100!)         right = 7 (h=8)
         |                            |                         |
         |~~~~~~~~~~~~...~~~~~~~~~~~~~|~~~~~~~~~~~~...~~~~~~~~~~|  (0, 7): width 7 * min(2, 8)   = 14
         |~~~~~~~~~~~~...~~~~~~~~~~~~~|                            (0, r'): width < 7 * min(2,100) < 14!
    

    Because every narrower tank keeping left has smaller width and height at most heights[left], none of them can beat (left, right). We can safely retire left via left += 1. Symmetrically, when heights[right] < heights[left], we retire right via right -= 1.

    What about a height tie (heights[left] == heights[right])? Neither left nor right can beat (left, right) with any partner strictly between them; any better tank inside [left, right] must use two interior walls both strictly taller than heights[left], so stepping left += 1 (via <=) never loses that interior pair.

  4. Code the two-pointer loop

    Each iteration evaluates the current rectangle, updates best_area, and moves the shorter wall inward by 1. Because right - left starts at n - 1 and shrinks by 1 per step, the loop runs n - 1 times.

    from typing import List
    
    
    def max_area(heights: List[int]) -> int:
        # Two pointers starting at the widest possible container: [0 .. len(heights) - 1].
        left = 0
        right = len(heights) - 1
        # best_area: largest water rectangle area seen across all evaluated (left, right) pairs.
        best_area = 0
    
        while left < right:
            width = right - left
            # Water spills over the shorter wall, so the container height is capped by the minimum.
            limiting_height = min(heights[left], heights[right])
            current_area = width * limiting_height
            if current_area > best_area:
                best_area = current_area
    
            # Every narrower pair keeping the shorter wall has smaller width and height <= limiting_height,
            # so dropping the shorter wall (or either wall on a tie via '<=') never misses a better pair.
            if heights[left] <= heights[right]:
                left += 1
            else:
                right -= 1
    
        return best_area
    
  5. Trace Example 1 step by step

    Let's trace heights = [2, 9, 4, 1, 6, 9, 3, 8]:

    step | left (h) | right (h) | width | min_h | area | best_area | pointer moved
    -----+----------+-----------+-------+-------+------+-----------+-------------------------
      1  |  0  (2)  |   7  (8)  |   7   |   2   |  14  |    14     | left -> 1  (2 <= 8)
      2  |  1  (9)  |   7  (8)  |   6   |   8   |  48  |    48     | right -> 6 (9 > 8)
      3  |  1  (9)  |   6  (3)  |   5   |   3   |  15  |    48     | right -> 5 (9 > 3)
      4  |  1  (9)  |   5  (9)  |   4   |   9   |  36  |    48     | left -> 2  (9 <= 9 tie)
      5  |  2  (4)  |   5  (9)  |   3   |   4   |  12  |    48     | left -> 3  (4 <= 9)
      6  |  3  (1)  |   5  (9)  |   2   |   1   |   2  |    48     | left -> 4  (1 <= 9)
      7  |  4  (6)  |   5  (9)  |   1   |   6   |   6  |    48     | left -> 5  (stop!)
    

    Notice how area rises and dips (14 -> 48 -> 15 -> 36 -> 12 -> 2 -> 6): we never halt early on a drop, and after 7 iterations (n - 1) we return 48.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def max_area(heights: List[int]) -> int:
        # Two pointers starting at the widest possible container: [0 .. len(heights) - 1].
        left = 0
        right = len(heights) - 1
        # best_area: largest water rectangle area seen across all evaluated (left, right) pairs.
        best_area = 0
    
        while left < right:
            width = right - left
            # Water spills over the shorter wall, so the container height is capped by the minimum.
            limiting_height = min(heights[left], heights[right])
            current_area = width * limiting_height
            if current_area > best_area:
                best_area = current_area
    
            # Every narrower pair keeping the shorter wall has smaller width and height <= limiting_height,
            # so dropping the shorter wall (or either wall on a tie via '<=') never misses a better pair.
            if heights[left] <= heights[right]:
                left += 1
            else:
                right -= 1
    
        return best_area
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine placing two vertical planks inside a long channel to serve as the left and right walls of a water tank: water spills over whichever plank is shorter, while any thin markers between them sit submerged without displacing water. Using the two-pointer technique (keeping two indices left = 0 and right = n - 1 at opposite ends of the list and stepping them inward), we start with the widest tank, record its area, and make a greedy choice (a locally optimal step that provably never discards the global optimum): always step the shorter plank inward. Holding onto the shorter plank while pulling the taller plank inward shrinks the width and still caps the water level at that exact same short plank, so the shorter plank can never achieve a larger tank with any inner partner!

Why does a naive search fail? Evaluating all n * (n - 1) / 2 wall pairs takes O(n^2) time — roughly 5 billion calculations at n = 10^5 — which times out. Stopping early as soon as the area drops also fails because short walls beside tall ones cause areas to dip before rebounding (6 -> 6 -> 7 below). Starting widest and retiring the shorter wall rules out up to n - 2 inferior pairs in O(1) time per step.

Here is a 4-wall trace on heights = [2, 8, 7, 3]:

Step 1: left=0 (h=2), right=3 (h=3) -> area = (3 - 0) * min(2, 3) = 6 | best = 6
        h=2 <= h=3, so left=0 cannot beat 6 with any inner wall -> left += 1

Step 2: left=1 (h=8), right=3 (h=3) -> area = (3 - 1) * min(8, 3) = 6 | best = 6
        h=8 > h=3, so right=3 cannot beat 6 with any inner wall -> right -= 1

Step 3: left=1 (h=8), right=2 (h=7) -> area = (2 - 1) * min(8, 7) = 7 | best = 7
        h=8 > h=7 -> right -= 1 (left == right == 1, loop ends)      -> returns 7

Complexity

Let n = len(heights) be the number of vertical walls.

  • Time: O(n). The span right - left begins at n - 1 and shrinks by 1 on each iteration until left == right, executing n - 1 iterations with O(1) arithmetic per step.
  • Space: O(1). Only six integer variables (left, right, best_area, width, limiting_height, current_area) are kept, independent of n.

Edge cases

  • Minimum length (n = 2, e.g., [4, 6] in Example 2): Executes one iteration with width = 1 and returns min(4, 6) = 4.
  • All zero heights ([0, 0, 0, 0]): Every pair has height 0, returning 0.
  • All identical heights ([4, 4, 4, 4, 4, 4]): The widest pair (0, 5) wins immediately with 5 * 4 = 20, and stepping left on ties scans cleanly to completion.
  • Zero-height walls in the interior ([3, 0, 0, 0, 3]): Interior walls do not block water, so (0, 4) returns 4 * 3 = 12.
  • Optimal pair strictly inside ([1, 9, 9, 1]): Both short outer 1s are retired first, revealing (1, 2) with area 9.
  • Upper constraint limits (n = 10^5, heights[i] = 10^4): Peak area is 99,999 * 10,000 = 999,990,000 (~10^9), fitting easily in Python integers as well as 32-bit signed integers in C++/Java.

Common mistakes

  • Stepping the taller wall inward instead of the shorter one: That pins one pointer on a short outer wall (such as 2 at index 0 in Example 1) and misses the winning pair (1, 7) of area 48.
  • Mixing up tank area with Trapping Rain Water: Walls here have zero thickness and form one open rectangle; never subtract intermediate wall heights or sum column-by-column water.
  • Off-by-one width (right - left + 1): Walls at coordinates 1 and 7 span 7 - 1 = 6 units, not 7.
  • Halting as soon as current_area drops: Areas along the inward sweep are not unimodal — stepping onto a short neighbor lowers the area temporarily before a taller inner wall raises it again.

Alternative approaches

  • All-pairs scan (O(n^2) time, O(1) space): Evaluates every (i, j) pair; too slow for n = 10^5, yet handy as an oracle in randomized tests on short lists.
  • Skipping consecutive shorter walls (O(n) time, O(1) space): After recording limiting_height, advance left while left < right and heights[left] <= limiting_height (and likewise for right). That avoids multiplications where neither width nor height can improve, shaving constant overhead while keeping O(n) worst-case time.

Follow-up questions

  • Suppose a valid tank must include at least one wall of height H or greater. How can you still find the largest area in linear time? First clarify whether "include" means anywhere across [left, right] or as one of the two tank walls — both run in O(n) time! If [left, right] must span some index k (left <= k <= right) with heights[k] >= H, build a prefix sum (prefix[k] = count of walls >= H in heights[:k]) and run the standard two-pointer sweep, updating best_area only when prefix[right + 1] - prefix[left] > 0 (when 0, no sub-interval inside [left, right] has a wall >= H either; when > 0, (left, right) is valid and still beats every dropped narrower pair). If instead at least one chosen endpoint must satisfy heights >= H, locate the earliest (first_tall) and latest (last_tall) indices >= H: pair every index i against first_tall and last_tall (covering all optimal tanks where one endpoint is < H), and run two pointers restricted to the subsequence of indices with heights[idx] >= H (covering tanks where both endpoints are >= H).
  • If wall heights arrive one by one from an unbounded-length stream, which candidate walls must you keep in memory before finalizing the answer? Because one giant wall at the very end of the stream can beat every earlier pair, no algorithm can finalize the answer mid-stream, and worst-case memory (for strictly rising heights) is O(n). Still, you only need to retain prefix maxima (walls strictly taller than every earlier wall, since any left wall is dominated by an earlier wall at least as tall) and suffix maxima (walls strictly taller than every later wall, maintained online with a decreasing monotonic stack), then run two pointers over those candidates at end-of-stream — cutting expected memory to O(log n) on randomly ordered streams!
  • Why is O(n) time with O(1) auxiliary space asymptotically optimal, and why can no deterministic algorithm skip inspecting elements? Every correct algorithm must inspect at least n - 1 entries in the worst case (Omega(n) time). Suppose an algorithm runs on heights = [0, 0, ..., 0] (true answer 0) and skips reading two positions i < j: an adversary could set both heights[i] = 1 and heights[j] = 1 (changing the true answer to j - i >= 1) without altering any cell the algorithm inspected, forcing it to return the wrong answer.

Follow-up questions

Similar questions

More eBay interview questions

All 41 eBay questions →