Bird
Raised Fist0
DSA Javascriptprogramming

Container With Most Water in DSA Javascript

Choose your learning style10 modes available
Mental Model
We want to find two lines that hold the most water between them by checking pairs from the edges inward.
Analogy: Imagine two walls on a beach holding water between them; the water amount depends on the shorter wall and the distance between them.
height array: [1] [8] [6] [2] [5] [4] [8] [3] [7]
indexes:     0   1   2   3   4   5   6   7   8
left pointer ↑                             right pointer ↑
Dry Run Walkthrough
Input: height = [1,8,6,2,5,4,8,3,7]
Goal: Find two lines that together with the x-axis form a container holding the most water.
Step 1: Start with left pointer at index 0 and right pointer at index 8, calculate area
left=0 (height=1), right=8 (height=7), area = min(1,7) * (8-0) = 1*8=8
Why: We check the widest container first to get a baseline area.
Step 2: Move left pointer from 0 to 1 because height at left is smaller
left=1 (height=8), right=8 (height=7), area = min(8,7) * (8-1) = 7*7=49
Why: Moving the smaller height pointer might find a taller line and larger area.
Step 3: Move right pointer from 8 to 7 because height at right is smaller
left=1 (height=8), right=7 (height=3), area = min(8,3) * (7-1) = 3*6=18
Why: Right height is smaller, so move right pointer inward to try taller line.
Step 4: Move right pointer from 7 to 6 because height at right is smaller
left=1 (height=8), right=6 (height=8), area = min(8,8) * (6-1) = 8*5=40
Why: Right height is smaller, move right pointer inward again.
Step 5: Move left pointer from 1 to 2 because height at left is smaller
left=2 (height=6), right=6 (height=8), area = min(6,8) * (6-2) = 6*4=24
Why: Left height smaller, move left pointer inward.
Step 6: Move left pointer from 2 to 3 because height at left is smaller
left=3 (height=2), right=6 (height=8), area = min(2,8) * (6-3) = 2*3=6
Why: Left height smaller, move left pointer inward.
Step 7: Move left pointer from 3 to 4 because height at left is smaller
left=4 (height=5), right=6 (height=8), area = min(5,8) * (6-4) = 5*2=10
Why: Left height smaller, move left pointer inward.
Step 8: Move left pointer from 4 to 5 because height at left is smaller
left=5 (height=4), right=6 (height=8), area = min(4,8) * (6-5) = 4*1=4
Why: Left height smaller, move left pointer inward.
Step 9: Move left pointer from 5 to 6, pointers meet, stop
left=6, right=6, pointers met, stop
Why: Pointers met, all pairs checked.
Result:
Maximum area found is 49 between indexes 1 and 8
Annotated Code
DSA Javascript
class ContainerWithMostWater {
  static maxArea(height) {
    let left = 0;
    let right = height.length - 1;
    let maxArea = 0;
    while (left < right) {
      // Calculate current area
      const width = right - left;
      const currentHeight = Math.min(height[left], height[right]);
      const currentArea = width * currentHeight;
      if (currentArea > maxArea) {
        maxArea = currentArea;
      }
      // Move pointer of smaller height inward
      if (height[left] < height[right]) {
        left++;
      } else {
        right--;
      }
    }
    return maxArea;
  }
}

// Driver code
const height = [1,8,6,2,5,4,8,3,7];
const result = ContainerWithMostWater.maxArea(height);
console.log(result);
while (left < right) {
loop until pointers meet to check all pairs
const width = right - left;
calculate distance between pointers
const currentHeight = Math.min(height[left], height[right]);
height limited by shorter line
const currentArea = width * currentHeight;
calculate area for current pair
if (currentArea > maxArea) { maxArea = currentArea; }
update max area if current is bigger
if (height[left] < height[right]) { left++; } else { right--; }
move pointer at smaller height inward to try bigger area
OutputSuccess
49
Complexity Analysis
Time: O(n) because we move pointers inward only once each, checking all pairs efficiently
Space: O(1) because we use only a few variables, no extra data structures
vs Alternative: Naive approach checks all pairs with nested loops O(n^2), this two-pointer method is much faster
Edge Cases
Empty array
Returns 0 as no container can be formed
DSA Javascript
while (left < right) {
Array with one element
Returns 0 as at least two lines are needed
DSA Javascript
while (left < right) {
All heights equal
Returns max area as height * (length-1)
DSA Javascript
if (currentArea > maxArea) { maxArea = currentArea; }
When to Use This Pattern
When asked to find max area or max volume between two points in a linear structure, use two pointers moving inward from edges to find optimal pair efficiently.
Common Mistakes
Mistake: Moving both pointers inward at the same time
Fix: Move only the pointer at the smaller height to potentially find a taller line and larger area
Mistake: Using nested loops to check all pairs
Fix: Use two-pointer approach to reduce time complexity from O(n^2) to O(n)
Summary
Finds two lines that form the container holding the most water by checking pairs from edges inward.
Use when you need to maximize area between two vertical lines in an array.
The key insight is to move the pointer at the smaller height inward to find a potentially larger area.

Practice

(1/5)
1. What does the "Container With Most Water" problem ask you to find given an array of heights?
easy
A. The maximum area formed between two lines representing container walls.
B. The minimum height in the array.
C. The sum of all heights in the array.
D. The difference between the tallest and shortest lines.

Solution

  1. Step 1: Understand the problem statement

    The problem asks to find two lines that together with the x-axis form a container that holds the most water.
  2. Step 2: Identify what to maximize

    The area between two lines is width (distance between lines) times the height (minimum of the two lines). We want the maximum such area.
  3. Final Answer:

    The maximum area formed between two lines representing container walls. -> Option A
  4. Quick Check:

    Max area = max water container [OK]
Hint: Look for two lines maximizing min height * distance [OK]
Common Mistakes:
  • Thinking it's about sum of heights
  • Confusing max height with max area
  • Ignoring the distance between lines
2. Which of the following JavaScript code snippets correctly initializes two pointers for the Container With Most Water problem?
easy
A. let left = 1, right = heights.length;
B. let left = -1, right = heights.length + 1;
C. let left = heights.length, right = 0;
D. let left = 0, right = heights.length - 1;

Solution

  1. Step 1: Identify correct pointer initialization

    We start with left pointer at index 0 and right pointer at last index (length - 1).
  2. Step 2: Check each option

    let left = 0, right = heights.length - 1; correctly sets left = 0 and right = heights.length - 1. Others use invalid indices.
  3. Final Answer:

    let left = 0, right = heights.length - 1; -> Option D
  4. Quick Check:

    Start pointers at array ends [OK]
Hint: Start pointers at array ends: 0 and length-1 [OK]
Common Mistakes:
  • Using invalid indices outside array bounds
  • Starting both pointers at same position
  • Confusing length with last index
3. What is the output of the following JavaScript code?
function maxArea(height) {
  let left = 0, right = height.length - 1;
  let max = 0;
  while (left < right) {
    const area = Math.min(height[left], height[right]) * (right - left);
    max = Math.max(max, area);
    if (height[left] < height[right]) {
      left++;
    } else {
      right--;
    }
  }
  return max;
}

console.log(maxArea([1,8,6,2,5,4,8,3,7]));
medium
A. 56
B. 49
C. 64
D. 72

Solution

  1. Step 1: Trace the two-pointer approach

    Start with left=0 (height=1), right=8 (height=7), area = min(1,7)*8=8. Max=8.
  2. Step 2: Move pointers and update max

    Since height[left]
  3. Final Answer:

    49 -> Option B
  4. Quick Check:

    Max area for input = 49 [OK]
Hint: Move pointer at smaller height inward to find max area [OK]
Common Mistakes:
  • Calculating area incorrectly using max height
  • Not updating max area properly
  • Moving wrong pointer in the loop
4. Identify the bug in this JavaScript function for Container With Most Water:
function maxArea(height) {
  let left = 0, right = height.length - 1;
  let max = 0;
  while (left < right) {
    const area = Math.min(height[left], height[right]) * (right - left);
    max = Math.max(max, area);
    if (height[left] < height[right]) {
      left++;
    } else {
      right++;
    }
  }
  return max;
}
medium
A. The right pointer should decrement (right--) instead of increment (right++).
B. The area calculation should use max instead of min height.
C. The max variable should be initialized to Infinity.
D. The loop condition should be left < right, not left <= right.

Solution

  1. Step 1: Check pointer movement logic

    The right pointer is incorrectly incremented (right++), which moves it out of array bounds.
  2. Step 2: Correct pointer movement

    When height[left] >= height[right], right pointer should move left (right--) to find a potentially larger area.
  3. Final Answer:

    The right pointer should decrement (right--) instead of increment (right++). -> Option A
  4. Quick Check:

    Right pointer moves left to reduce width [OK]
Hint: Right pointer moves left (decrement) to find max area [OK]
Common Mistakes:
  • Using right++ instead of right--
  • Loop condition allowing left == right
  • Incorrect area calculation using max height
5. Given an array of heights, how would you modify the Container With Most Water algorithm to also return the indices of the two lines forming the container with the maximum water?
hard
A. Sort the array and return indices of the tallest two lines.
B. Return the first two indices always, as they form the max container.
C. Track indices when updating max area and return them along with max area.
D. Use a nested loop to check all pairs and return the last pair found.

Solution

  1. Step 1: Add variables to track indices

    Initialize variables to store left and right indices when max area updates.
  2. Step 2: Update indices when max area changes

    Inside the loop, when a new max area is found, save current left and right indices.
  3. Step 3: Return max area and indices

    Return an object or array containing max area and the two indices after loop ends.
  4. Final Answer:

    Track indices when updating max area and return them along with max area. -> Option C
  5. Quick Check:

    Save indices on max update for output [OK]
Hint: Save indices when max area updates during pointer moves [OK]
Common Mistakes:
  • Returning fixed indices without checking area
  • Sorting array loses original indices
  • Using nested loops increases time complexity
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard