Bird
Raised Fist0
DSA Rustprogramming

Container With Most Water in DSA Rust

Choose your learning style10 modes available
Mental Model
We want to find two lines that hold the most water between them by maximizing the area formed by their heights and the distance between them.
Analogy: Imagine two vertical walls on a beach holding water between them. The water amount depends on the shorter wall and the distance between walls.
height array: [1] [8] [6] [2] [5] [4] [8] [3] [7]
indexes:      0    1    2    3    4    5    6    7    8

Visual:
|        ↑
|        |        ↑
|        |        |        ↑
|        |        |        |        ↑
|        |        |        |        |        ↑
|        |        |        |        |        |        ↑
|        |        |        |        |        |        |        ↑
|        |        |        |        |        |        |        |        ↑
|________|________|________|________|________|________|________|________|________
  0        1        2        3        4        5        6        7        8
Dry Run Walkthrough
Input: height array: [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: Initialize left pointer at index 0 and right pointer at index 8
left=0 (height=1), right=8 (height=7), max_area=0
Why: Start with the widest container possible to maximize area.
Step 2: Calculate area between left and right: min(1,7) * (8-0) = 1*8=8, update max_area=8
max_area=8
Why: Area depends on shorter line and distance between pointers.
Step 3: Move left pointer right because height[left] < height[right]
left=1 (height=8), right=8 (height=7), max_area=8
Why: Moving the shorter line might find a taller line to increase area.
Step 4: Calculate area: min(8,7) * (8-1) = 7*7=49, update max_area=49
max_area=49
Why: Found a bigger area, update max_area.
Step 5: Move right pointer left because height[right] < height[left]
left=1 (height=8), right=7 (height=3), max_area=49
Why: Try to find a taller line on the right side.
Step 6: Calculate area: min(8,3) * (7-1) = 3*6=18, max_area=49 stays
max_area=49
Why: Area smaller than max_area, no update.
Step 7: Move right pointer left again because height[right] < height[left]
left=1 (height=8), right=6 (height=8), max_area=49
Why: Try to find taller or equal height line.
Step 8: Calculate area: min(8,8) * (6-1) = 8*5=40, max_area=49 stays
max_area=49
Why: Area smaller than max_area, no update.
Step 9: Move left pointer right because height[left] <= height[right]
left=2 (height=6), right=6 (height=8), max_area=49
Why: Try to find taller line on left side.
Step 10: Calculate area: min(6,8) * (6-2) = 6*4=24, max_area=49 stays
max_area=49
Why: Area smaller than max_area, no update.
Step 11: Move left pointer right because height[left] < height[right]
left=3 (height=2), right=6 (height=8), max_area=49
Why: Try to find taller line on left side.
Step 12: Calculate area: min(2,8) * (6-3) = 2*3=6, max_area=49 stays
max_area=49
Why: Area smaller than max_area, no update.
Step 13: Move left pointer right because height[left] < height[right]
left=4 (height=5), right=6 (height=8), max_area=49
Why: Try to find taller line on left side.
Step 14: Calculate area: min(5,8) * (6-4) = 5*2=10, max_area=49 stays
max_area=49
Why: Area smaller than max_area, no update.
Step 15: Move left pointer right because height[left] < height[right]
left=5 (height=4), right=6 (height=8), max_area=49
Why: Try to find taller line on left side.
Step 16: Calculate area: min(4,8) * (6-5) = 4*1=4, max_area=49 stays
max_area=49
Why: Area smaller than max_area, no update.
Step 17: Move left pointer right because height[left] < height[right]
left=6 (height=8), right=6 (height=8), max_area=49
Why: Pointers meet, end search.
Result:
max_area=49
Annotated Code
DSA Rust
fn max_area(height: Vec<i32>) -> i32 {
    let mut left = 0;
    let mut right = height.len() - 1;
    let mut max_area = 0;

    while left < right {
        let width = (right - left) as i32;
        let h = if height[left] < height[right] { height[left] } else { height[right] };
        let area = h * width;
        if area > max_area {
            max_area = area; // update max area if current is bigger
        }

        if height[left] < height[right] {
            left += 1; // move left pointer right to find taller line
        } else {
            right -= 1; // move right pointer left to find taller line
        }
    }

    max_area
}

fn main() {
    let height = vec![1,8,6,2,5,4,8,3,7];
    let result = max_area(height);
    println!("{}", result);
}
while left < right {
loop until pointers meet to check all container widths
let width = (right - left) as i32;
calculate current width between pointers
let h = if height[left] < height[right] { height[left] } else { height[right] };
choose shorter height as container height
let area = h * width;
calculate area with current pointers
if area > max_area { max_area = area; }
update max_area if current area is larger
if height[left] < height[right] { left += 1; } else { right -= 1; }
move pointer at shorter line inward to try larger area
OutputSuccess
49
Complexity Analysis
Time: O(n) because we move two pointers inward only once through the array
Space: O(1) because we use only a few variables regardless of input size
vs Alternative: Naive approach checks all pairs with O(n^2) time, this two-pointer method is much faster.
Edge Cases
Empty array
Returns 0 as no container can be formed
DSA Rust
while left < right {
Array with one element
Returns 0 as at least two lines are needed
DSA Rust
while left < right {
All heights equal
Returns max area as height * (length-1)
DSA Rust
if area > max_area { max_area = area; }
When to Use This Pattern
When asked to find max area or max product involving pairs in a linear structure, use two pointers moving inward to optimize search.
Common Mistakes
Mistake: Moving the pointer at the taller line instead of the shorter line
Fix: Always move the pointer at the shorter line inward to potentially find a taller line and increase area.
Summary
Finds the maximum water container area between two lines in an array.
Use when you need to maximize area formed by two heights and their distance.
The key is moving the pointer at the shorter line inward to find a better container.

Practice

(1/5)
1. What does the problem Container With Most Water ask you to find given an array of heights?
easy
A. The maximum area formed between two vertical lines and the x-axis
B. The minimum height in the array
C. The sum of all heights
D. The longest increasing subsequence of heights

Solution

  1. Step 1: Understand the problem statement

    The problem asks to find two lines that together with the x-axis form a container holding the most water, which means maximizing the area between them.
  2. Step 2: Identify what to calculate

    The area is calculated by the distance between the two lines multiplied by the smaller height of the two lines.
  3. Final Answer:

    The maximum area formed between two vertical lines and the x-axis -> Option A
  4. Quick Check:

    Container with most water = max area between lines [OK]
Hint: Look for two lines maximizing width x min height [OK]
Common Mistakes:
  • Confusing sum of heights with area
  • Choosing tallest lines without considering distance
  • Ignoring the smaller height between two lines
2. Which Rust code snippet correctly declares a vector of heights for the Container With Most Water problem?
easy
A. let heights = {1, 8, 6, 2, 5, 4, 8, 3, 7};
B. let heights = vec![1, 8, 6, 2, 5, 4, 8, 3, 7];
C. let heights = (1, 8, 6, 2, 5, 4, 8, 3, 7);
D. let heights = [1, 8, 6, 2, 5, 4, 8, 3, 7];

Solution

  1. Step 1: Identify Rust vector syntax

    In Rust, a vector is declared using vec![...] macro to create a growable array.
  2. Step 2: Check each option

    let heights = vec![1, 8, 6, 2, 5, 4, 8, 3, 7]; uses vec![...] correctly. let heights = [1, 8, 6, 2, 5, 4, 8, 3, 7]; is an array, not a vector. let heights = (1, 8, 6, 2, 5, 4, 8, 3, 7); is a tuple. let heights = {1, 8, 6, 2, 5, 4, 8, 3, 7}; uses braces which is invalid syntax.
  3. Final Answer:

    let heights = vec![1, 8, 6, 2, 5, 4, 8, 3, 7]; -> Option B
  4. Quick Check:

    Vector syntax = vec![...] [OK]
Hint: Use vec![...] for vectors in Rust [OK]
Common Mistakes:
  • Using array syntax instead of vector
  • Using tuple parentheses instead of brackets
  • Using braces which is invalid
3. What is the output of this Rust code snippet that finds the max water container area?
fn max_area(height: Vec<i32>) -> i32 {
    let mut left = 0;
    let mut right = height.len() - 1;
    let mut max_area = 0;
    while left < right {
        let width = (right - left) as i32;
        let h = if height[left] < height[right] { height[left] } else { height[right] };
        let area = width * h;
        if area > max_area {
            max_area = area;
        }
        if height[left] < height[right] {
            left += 1;
        } else {
            right -= 1;
        }
    }
    max_area
}

fn main() {
    let heights = vec![1,8,6,2,5,4,8,3,7];
    println!("{}", max_area(heights));
}
medium
A. 48
B. 56
C. 64
D. 49

Solution

  1. Step 1: Understand the two-pointer approach

    Start with left at 0 and right at last index, calculate area, move pointer with smaller height inward.
  2. Step 2: Trace the code with given heights

    Max area found is between height 8 at index 1 and height 7 at index 8, width = 7, area = 7 * 7 = 49.
  3. Final Answer:

    49 -> Option D
  4. Quick Check:

    Max area = 49 [OK]
Hint: Use two pointers, move smaller height inward [OK]
Common Mistakes:
  • Calculating area with max height instead of min
  • Not updating max area correctly
  • Moving wrong pointer in the loop
4. Identify the bug in this Rust function for Container With Most Water and select the fix:
fn max_area(height: Vec<i32>) -> i32 {
    let mut left = 0;
    let mut right = height.len();
    let mut max_area = 0;
    while left < right {
        let width = (right - left) as i32;
        let h = if height[left] < height[right] { height[left] } else { height[right] };
        let area = width * h;
        if area > max_area {
            max_area = area;
        }
        if height[left] < height[right] {
            left += 1;
        } else {
            right -= 1;
        }
    }
    max_area
}
medium
A. Change right initialization to height.len() - 1
B. Change while condition to left <= right
C. Use max instead of min height for area calculation
D. Remove the if condition inside the loop

Solution

  1. Step 1: Check initialization of right pointer

    Rust vectors are zero-indexed, so last index is length - 1, not length.
  2. Step 2: Identify impact of wrong right pointer

    Using length causes out-of-bounds access when accessing height[right], leading to runtime error.
  3. Final Answer:

    Change right initialization to height.len() - 1 -> Option A
  4. Quick Check:

    Right pointer = last index = len() - 1 [OK]
Hint: Index last element with len() - 1, not len() [OK]
Common Mistakes:
  • Using length as index causing panic
  • Changing loop condition incorrectly
  • Using max height instead of min for area
5. Given a vector of heights, how would you modify the two-pointer approach to also return the indices of the two lines forming the container with the most water?
hard
A. Return the sum of the two heights instead of area
B. Use a nested loop to check all pairs and store indices of max area
C. Keep track of max_area and update a tuple (left_index, right_index) whenever max_area changes
D. Only return the left pointer index as the answer

Solution

  1. Step 1: Understand the two-pointer approach

    We move pointers inward and calculate area at each step, updating max area found.
  2. Step 2: Track indices when max area updates

    Along with max_area, store the current left and right indices whenever a larger area is found.
  3. Final Answer:

    Keep track of max_area and update a tuple (left_index, right_index) whenever max_area changes -> Option C
  4. Quick Check:

    Track indices with max area updates [OK]
Hint: Update indices when max area changes [OK]
Common Mistakes:
  • Returning sum instead of area
  • Using nested loops losing O(n) efficiency
  • Returning only one index instead of both
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