Bird
Raised Fist0
DSA C++programming~10 mins

Container With Most Water in DSA C++ - Execution Trace

Choose your learning style10 modes available
Concept Flow - Container With Most Water
Start with two pointers
↓
Calculate area between left and right
↓
Update max area if current area is larger
↓
Move pointer with smaller height inward
↓
left++ if height[left
↓
Repeat until left meets right
↓
Return max area found
Start with two pointers at ends, calculate area, move the smaller height pointer inward, update max area, repeat until pointers meet.
Execution Sample
DSA C++
int maxArea(vector<int>& height) {
  int left = 0, right = height.size() - 1;
  int max_area = 0;
  while (left < right) {
    int area = min(height[left], height[right]) * (right - left);
    max_area = max(max_area, area);
    if (height[left] < height[right]) left++; else right--;
  }
  return max_area;
}
Calculates the maximum water container area by moving two pointers inward based on height comparison.
Execution Table
StepOperationLeft PointerRight PointerHeight[left]Height[right]Area CalculatedMax AreaPointer MovedVisual State
1Initialize pointers0813min(1,3)*8=88Move left pointer (height[left]<height[right])[1,8,6,2,5,4,8,7,3]
2Calculate area1883min(8,3)*7=2121Move right pointer (height[right]<=height[left])[1,8,6,2,5,4,8,7,3]
3Calculate area1787min(8,7)*6=4242Move right pointer (height[right]<=height[left])[1,8,6,2,5,4,8,7,3]
4Calculate area1688min(8,8)*5=4042Move right pointer (height[right]<=height[left])[1,8,6,2,5,4,8,7,3]
5Calculate area1584min(8,4)*4=1642Move right pointer (height[right]<=height[left])[1,8,6,2,5,4,8,7,3]
6Calculate area1485min(8,5)*3=1542Move right pointer (height[right]<=height[left])[1,8,6,2,5,4,8,7,3]
7Calculate area1382min(8,2)*2=442Move right pointer (height[right]<=height[left])[1,8,6,2,5,4,8,7,3]
8Calculate area1286min(8,6)*1=642Move right pointer (height[right]<=height[left])[1,8,6,2,5,4,8,7,3]
9Pointers meet1188Stop42Stop[1,8,6,2,5,4,8,7,3]
💡 Left pointer meets right pointer, loop ends.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 6After Step 7After Step 8Final
left0111111111
right8876543211
max_area082142424242424242
Key Moments - 3 Insights
Why do we move the pointer with the smaller height?
Because the area depends on the smaller height, moving the taller pointer won't increase area. See steps 1 and 2 in execution_table where moving the smaller height pointer leads to larger area.
Why does the loop stop when left meets right?
When left equals right, there is no width between pointers, so area is zero. The exit_note and step 9 in execution_table show this stopping condition.
Why do we calculate area using min(height[left], height[right]) * (right - left)?
The container's water is limited by the shorter line and the distance between pointers. This formula is used in every step's 'Area Calculated' column in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the max_area after step 3?
A21
B42
C40
D8
💡 Hint
Check the 'Max Area' column at step 3 in execution_table.
At which step does the right pointer first move?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Pointer Moved' column in execution_table for the first right pointer move.
If height[left] was always greater than height[right], which pointer would move?
ABoth pointers move simultaneously
BLeft pointer moves
CRight pointer moves
DNo pointer moves
💡 Hint
Refer to the condition in the code and pointer movement logic in execution_table.
Concept Snapshot
Container With Most Water:
- Use two pointers at array ends
- Calculate area = min(height[left], height[right]) * distance
- Move pointer with smaller height inward
- Update max area each step
- Stop when pointers meet
- Returns max water container area
Full Transcript
This concept uses two pointers starting at the ends of the height array. At each step, it calculates the area formed by the lines at these pointers and the distance between them. The maximum area is updated if the current area is larger. Then, the pointer at the smaller height moves inward to try to find a taller line that could increase the area. This repeats until the pointers meet, at which point the maximum area found is returned.

Practice

(1/5)
1. What is the main goal of the Container With Most Water problem?
easy
A. Find two lines that together with the x-axis form a container holding the most water
B. Sort the array of heights in ascending order
C. Find the maximum height in the array
D. Calculate the sum of all heights

Solution

  1. Step 1: Understand the problem statement

    The problem asks to find two vertical lines which, together with the x-axis, form a container that holds the maximum amount of water.
  2. Step 2: Identify what is being maximized

    The area between two lines is calculated by the minimum height of the two lines multiplied by the distance between them. We want to maximize this area.
  3. Final Answer:

    Find two lines that together with the x-axis form a container holding the most water -> Option A
  4. Quick Check:

    Goal = Max water container [OK]
Hint: Max area = min height * width between lines [OK]
Common Mistakes:
  • Thinking it's about sorting heights
  • Trying to sum heights instead of area
  • Looking for max single height only
2. Which of the following C++ code snippets correctly initializes two pointers for the two-pointer approach in the Container With Most Water problem?
easy
A. int left = 1, right = heights.size();
B. int left = 0, right = heights.size() - 1;
C. int left = 0, right = heights.size();
D. int left = 1, right = heights.size() - 1;

Solution

  1. Step 1: Understand pointer initialization

    We start with two pointers: one at the beginning (index 0) and one at the end (index size-1) of the array.
  2. Step 2: Check each option

    int left = 0, right = heights.size() - 1; correctly sets left = 0 and right = size - 1, which are valid indices. Other options use invalid indices or off-by-one errors.
  3. Final Answer:

    int left = 0, right = heights.size() - 1; -> Option B
  4. Quick Check:

    Pointers start at ends = int left = 0, right = heights.size() - 1; [OK]
Hint: Start pointers at array ends: 0 and size-1 [OK]
Common Mistakes:
  • Using size() as index (out of bounds)
  • Starting pointers at 1 instead of 0
  • Swapping left and right initialization
3. What is the output of the following C++ code snippet?
std::vector<int> heights = {1, 8, 6, 2, 5, 4, 8, 3, 7};
int left = 0, right = heights.size() - 1;
int maxArea = 0;
while (left < right) {
    int height = std::min(heights[left], heights[right]);
    int width = right - left;
    maxArea = std::max(maxArea, height * width);
    if (heights[left] < heights[right]) {
        left++;
    } else {
        right--;
    }
}
std::cout << maxArea << std::endl;
medium
A. 56
B. 50
C. 48
D. 49

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. Move left pointer since height[left]
  2. Step 2: Continue updating maxArea

    Next left=1 (8), right=8 (7), area= min(8,7)*7=49 (maxArea=49). Move right pointer since height[left]>height[right]. Then left=1, right=7 (3), area= min(8,3)*6=18 (maxArea=49). Move right pointer. Continue similarly until pointers meet. The maximum area found is 49.
  3. Final Answer:

    49 -> Option D
  4. Quick Check:

    Max area = 49 [OK]
Hint: Move pointer at smaller height to find max area [OK]
Common Mistakes:
  • Not updating maxArea correctly
  • Moving wrong pointer after comparison
  • Calculating area with max height instead of min
4. Identify the bug in the following code snippet for the Container With Most Water problem:
int maxArea(std::vector<int>& heights) {
    int left = 0, right = heights.size();
    int max_area = 0;
    while (left < right) {
        int height = std::min(heights[left], heights[right]);
        int width = right - left;
        max_area = std::max(max_area, height * width);
        if (heights[left] < heights[right]) {
            left++;
        } else {
            right--;
        }
    }
    return max_area;
}
medium
A. The loop condition should be left <= right
B. Use max instead of min to calculate height
C. right should be initialized to heights.size() - 1
D. Increment right instead of decrementing

Solution

  1. Step 1: Check pointer initialization

    right is initialized to heights.size(), which is out of bounds since valid indices go up to size()-1.
  2. Step 2: Correct initialization and loop condition

    right should be heights.size() - 1 to point to the last valid element. The loop condition left < right is correct.
  3. Final Answer:

    right should be initialized to heights.size() - 1 -> Option C
  4. Quick Check:

    Index out of bounds fixed by right should be initialized to heights.size() - 1 [OK]
Hint: Array indices go from 0 to size-1 [OK]
Common Mistakes:
  • Using size() as index causing runtime error
  • Changing loop condition incorrectly
  • Using max instead of min for height
5. Given an array of heights representing vertical lines, how would you modify the two-pointer approach to find the maximum water container if the array can contain zero heights (lines with zero height)?
hard
A. Skip zero height lines by moving pointers inward until non-zero heights are found
B. Treat zero heights as normal and proceed with the standard two-pointer approach
C. Remove zero height lines from the array before processing
D. Use a nested loop to check all pairs instead of two-pointer

Solution

  1. Step 1: Understand zero height impact

    Lines with zero height cannot hold water, so including them wastes time and area calculations.
  2. Step 2: Modify two-pointer approach

    Skip zero height lines by moving pointers inward until both point to non-zero heights. Then apply the standard two-pointer logic to maximize area.
  3. Final Answer:

    Skip zero height lines by moving pointers inward until non-zero heights are found -> Option A
  4. Quick Check:

    Skip zeros for max area [OK]
Hint: Ignore zero heights by moving pointers inward [OK]
Common Mistakes:
  • Processing zero height lines as normal
  • Removing elements changes indices and complicates logic
  • Switching to nested loops loses efficiency
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