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(height9) and the wall at index7(height8) yields width7 - 1 = 6and water heightmin(9, 8) = 8, producing area6 * 8 = 48. Pairing the two height-9walls at indices1and5gives a taller water level (9) but narrower width (5 - 1 = 4), reaching only36.
Example 2
- Input:
heights = [4, 6] - Output:
4 - Walk-through: Only one pair
(0, 1)exists, with width1 - 0 = 1and water heightmin(4, 6) = 4, for an area of1 * 4 = 4.
Constraints
2 <= len(heights) <= 10^50 <= heights[i] <= 10^4
Step-by-step walkthrough
Understand the geometry of a tank
Picking any two vertical walls at positions
left < rightforms an upright rectangle withy = 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 = 48We want the largest area across all pairs
0 <= left < right < n, wherencan reach10^5.- Width: horizontal span
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_areaAt
n = 10^5, there aren * (n - 1) / 2— nearly5 * 10^9— pairs (O(n^2)time), which is far too slow. ReachingO(n)time requires discarding an entire family of inferior pairs on every step.Key insight: start widest and discard the shorter wall
Start with two pointers at the far ends:
left = 0andright = 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 partnerr'(left < r' < right) paired withleft:- Strictly smaller width:
r' - left < right - left. - Water height still capped by
left:min(heights[left], heights[r']) <= heights[left], regardless of how tallheights[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
lefthas smaller width and height at mostheights[left], none of them can beat(left, right). We can safely retireleftvialeft += 1. Symmetrically, whenheights[right] < heights[left], we retirerightviaright -= 1.What about a height tie (
heights[left] == heights[right])? Neitherleftnorrightcan beat(left, right)with any partner strictly between them; any better tank inside[left, right]must use two interior walls both strictly taller thanheights[left], so steppingleft += 1(via<=) never loses that interior pair.- Strictly smaller width:
Code the two-pointer loop
Each iteration evaluates the current rectangle, updates
best_area, and moves the shorter wall inward by1. Becauseright - leftstarts atn - 1and shrinks by1per step, the loop runsn - 1times.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_areaTrace 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
arearises and dips (14 -> 48 -> 15 -> 36 -> 12 -> 2 -> 6): we never halt early on a drop, and after7iterations (n - 1) we return48.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 spanright - leftbegins atn - 1and shrinks by1on each iteration untilleft == right, executingn - 1iterations withO(1)arithmetic per step. - Space:
O(1). Only six integer variables (left,right,best_area,width,limiting_height,current_area) are kept, independent ofn.
Edge cases
- Minimum length (
n = 2, e.g.,[4, 6]in Example 2): Executes one iteration withwidth = 1and returnsmin(4, 6) = 4. - All zero heights (
[0, 0, 0, 0]): Every pair has height0, returning0. - All identical heights (
[4, 4, 4, 4, 4, 4]): The widest pair(0, 5)wins immediately with5 * 4 = 20, and steppinglefton 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)returns4 * 3 = 12. - Optimal pair strictly inside (
[1, 9, 9, 1]): Both short outer1s are retired first, revealing(1, 2)with area9. - Upper constraint limits (
n = 10^5,heights[i] = 10^4): Peak area is99,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
2at index0in Example 1) and misses the winning pair(1, 7)of area48. - 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 coordinates1and7span7 - 1 = 6units, not7. - Halting as soon as
current_areadrops: 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 forn = 10^5, yet handy as an oracle in randomized tests on short lists. - Skipping consecutive shorter walls (
O(n)time,O(1)space): After recordinglimiting_height, advanceleftwhileleft < right and heights[left] <= limiting_height(and likewise forright). That avoids multiplications where neither width nor height can improve, shaving constant overhead while keepingO(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 inO(n)time! If[left, right]must span some indexk(left <= k <= right) withheights[k] >= H, build a prefix sum (prefix[k]= count of walls>= Hinheights[:k]) and run the standard two-pointer sweep, updatingbest_areaonly whenprefix[right + 1] - prefix[left] > 0(when0, no sub-interval inside[left, right]has a wall>= Heither; when> 0,(left, right)is valid and still beats every dropped narrower pair). If instead at least one chosen endpoint must satisfyheights >= H, locate the earliest (first_tall) and latest (last_tall) indices>= H: pair every indexiagainstfirst_tallandlast_tall(covering all optimal tanks where one endpoint is< H), and run two pointers restricted to the subsequence of indices withheights[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 toO(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 - 1entries in the worst case (Omega(n)time). Suppose an algorithm runs onheights = [0, 0, ..., 0](true answer0) and skips reading two positionsi < j: an adversary could set bothheights[i] = 1andheights[j] = 1(changing the true answer toj - i >= 1) without altering any cell the algorithm inspected, forcing it to return the wrong answer.
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?
- If wall heights arrive one by one from an unbounded-length stream, which candidate walls must you keep in memory before finalizing the answer?
- Why is O(n) time with O(1) auxiliary space asymptotically optimal, and why can no deterministic algorithm skip inspecting elements?
Similar questions
- Randomized Ad Slot Allocation Under Per-User Caps
- Days Until a Higher Temperature
- Count Orthogonal Land Regions
- Shortest Path for a Leg-Blocked Xiangqi Horse
- Validate Numeric String Grammar
- Top K Frequent Integers
More eBay interview questions
- Days Until a Higher Temperature Medium
- Repeated Function Application and Core Data Structure Complexity Medium
- Randomized Ad Slot Allocation Under Per-User Caps Medium Pro
- Cross-Team Ownership, Manager Disagreements, and Slipping Skip-Level Deadlines Easy Pro
- Global Org Fit, Role Alignment, and On-Call Ownership Easy Pro
- Marketplace Payment Dispute Resolution Service Medium Pro
- Workplace Lunch Ordering with Daily Vendor Rotation Medium Pro
- Marketplace Product Search and Typeahead System Medium Pro
- Real-Time Top-10 Marketplace Bestseller Leaderboard Medium Pro
- Frequency-Capped Ad Placement API Medium Pro