Bird
Raised Fist0
DSA C++programming~30 mins

Container With Most Water in DSA C++ - Build from Scratch

Choose your learning style10 modes available
Container With Most Water
📖 Scenario: Imagine you have a row of vertical lines on a graph. Each line's height is given. You want to find two lines that, together with the x-axis, form a container that holds the most water.This is like choosing two walls to hold water between them. The water amount depends on the shorter wall and the distance between the walls.
🎯 Goal: You will write a program to find the maximum amount of water that can be contained between two lines from a list of heights.
📋 What You'll Learn
Create a vector called heights with the exact values: 1, 8, 6, 2, 5, 4, 8, 3, 7
Create two integer variables left and right to represent the start and end indices of the vector
Use a while loop to move left and right pointers to find the maximum water container
Print the maximum water amount as an integer
💡 Why This Matters
🌍 Real World
This problem models situations where you want to maximize capacity between boundaries, like storing water or optimizing space between walls.
💼 Career
Understanding two-pointer techniques and optimization is useful in coding interviews and real-world problems involving arrays and searching.
Progress0 / 4 steps
1
Create the heights vector
Create a std::vector<int> called heights with these exact values: 1, 8, 6, 2, 5, 4, 8, 3, 7
DSA C++
Hint

Use std::vector<int> heights = { ... }; to create the vector with the exact numbers.

2
Initialize left and right pointers
Create two integer variables called left and right. Set left to 0 and right to heights.size() - 1
DSA C++
Hint

Use int left = 0; and int right = heights.size() - 1; to set the pointers.

3
Find the maximum water container
Create an integer variable maxWater and set it to 0. Use a while loop with the condition left < right. Inside the loop, calculate the current water as the minimum of heights[left] and heights[right] multiplied by right - left. Update maxWater if current water is greater. Move left forward if heights[left] is less than heights[right], otherwise move right backward.
DSA C++
Hint

Use a while loop and update maxWater inside it. Move left or right based on which height is smaller.

4
Print the maximum water amount
Print the value of maxWater using std::cout
DSA C++
Hint

Use std::cout << maxWater << std::endl; to print the result.

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