DSA Patterns (Multi-Lang)•Part 3: Two Pointers & Sliding Window (19 - 28)
Container With Most Water.
In Simple Words:
Two pointers at extremes. Water capacity is bounded by the shorter line: min(h[l], h[r]) * (r - l). Always shift the pointer with the smaller height inward to potentially find taller vertical bars.
- Time: $O(N)$ | Space: $O(1)$
Multi-Language SolutionsPython 3 • JavaScript • TypeScript • Java • C++
Switch tabs or choose Alldef maxArea(height: list[int]) -> int:
l, r = 0, len(height) - 1
max_w = 0
while l < r:
area = min(height[l], height[r]) * (r - l)
max_w = max(max_w, area)
if height[l] < height[r]:
l += 1
else:
r -= 1
return max_w