MEDIUM NC#13 Blind #10 Two Pointers

11. Container With Most Water

๐Ÿ“– Problem

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.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขIn-place array updates
  • โ€ขSorted array traversal
  • โ€ขBoundary condition checks

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Two Pointers reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use two pointers at both ends
  • โ†’ Area = min(height[left], height[right]) * (right - left)
  • โ†’ Move the pointer with smaller height inward
  • โ†’ The goal is to find taller lines that are farther apart
  • โ†’ Time: O(n), Space: O(1)

๐Ÿงญ Prerequisites

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse two pointers at both ends
  • โ€ขArea = min(height[left], height[right]) * (right - left)
  • โ€ขMove the pointer with smaller height inward

Common Pitfalls

  • โ€ขThe goal is to find taller lines that are farther apart
  • โ€ขTime: O(n), Space: O(1)

๐Ÿงช Test Cases

Hidden tests on submit: 2

Test Case 1
Not run
Input:
maxArea([1,8,6,2,5,4,8,3,7]);
Expected:
49
Test Case 2
Not run
Input:
maxArea([1,1]);
Expected:
1
Test Case 3
Not run
Input:
maxArea([4,3,2,1,4]);
Expected:
16

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit