LeetCode Problem 11: Container With Most Water | Efficient Two-Pointer Strategy πŸš€

LeetCode Problem 11: Container With Most Water

Looking for the fastest way to solve the Container With Most Water problem? This guide walks you through the optimal two-pointer approach, complete with Java code, detailed explanation, and complexity analysis. Whether you’re prepping for interviews or brushing up on algorithms, this one’s a must-know!


🧠 Problem Overview

You’re given an array height where each element represents the height of a vertical line drawn at that index. The goal is to find two lines that, together with the x-axis, form a container that can hold the most water.

πŸ” Example

  • Input: height = [1,8,6,2,5,4,8,3,7]
  • Output: 49
  • Why? Lines at indices 1 and 8 β†’ min(8,7) * (8βˆ’1) = 7 * 7 = 49

πŸš€ Why Use the Two-Pointer Technique?

A brute-force solution checks all pairs of lines β€” that’s O(nΒ²) time! The two-pointer method trims this down to O(n) by using a clever strategy to skip unnecessary checks.

🧩 Key Idea:

Move the pointers inward in a way that maximizes the area potential.

πŸ’‘ Strategy:

  1. Start with two pointers: left at 0 and right at the end of the array.
  2. At each step:
    • Calculate area: min(height[left], height[right]) * (right - left)
    • Update maxArea if current area is larger.
    • Move the shorter line inward, hoping to find a taller line that may increase the area.

βœ… Java Implementation

class Solution {
    public int maxArea(int[] height) {
        int left = 0, right = height.length - 1;
        int maxArea = 0;

        while (left < right) {
            int h = Math.min(height[left], height[right]);
            int w = right - left;
            maxArea = Math.max(maxArea, h * w);

            // Move the pointer pointing to the shorter line
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return maxArea;
    }
}

πŸ“Š Complexity Analysis

  • Time Complexity: O(n) – Each index is visited once.
  • Space Complexity: O(1) – Constant space usage with only two pointers.

πŸ”„ How It Works – Step-by-Step

Let’s break it down with height = [1,8,6,2,5,4,8,3,7]:

  1. left = 0 (height = 1), right = 8 (height = 7)
    β†’ Area = 1 * 8 = 8
  2. Move left to 1 (height = 8), now area = 7 * 7 = 49 βœ…
  3. Move right to 7 (height = 3), area = 3 * 6 = 18
  4. Keep shifting inward and tracking max area…

Repeat until left meets right.


⚠️ Common Pitfalls to Avoid

  1. Forgetting to track the max area: Always compare and update maxArea.
  2. Wrong pointer movement: Only move the pointer pointing to the shorter line.
  3. Neglecting edge cases: For example, arrays with all equal heights or just two elements.

🌍 Real-World Applications

  • Urban Planning: Design water reservoirs between structures.
  • Logistics: Maximize container capacity using spatial constraints.
  • Chart Design: Optimize layout in data visualizations.

πŸ†š Brute Force (Not Recommended for Large Inputs)

int maxArea = 0;
for (int i = 0; i < height.length; i++) {
    for (int j = i + 1; j < height.length; j++) {
        int area = Math.min(height[i], height[j]) * (j - i);
        maxArea = Math.max(maxArea, area);
    }
}
return maxArea;
  • Time Complexity: O(nΒ²)
  • Space Complexity: O(1)

Use this only for understanding or very small inputs.


πŸ“Œ Why This Problem Matters

This is a classic problem for testing your two-pointer techniqueβ€”a powerful strategy for solving problems efficiently with linear time. It’s frequently asked in interviews at top tech companies like Google, Amazon, and Meta.


βœ… Related Problems to Practice

  • Trapping Rain Water (Harder variant)
  • Two Sum
  • Longest Substring Without Repeating Characters

πŸ”š Conclusion

Mastering the two-pointer approach here helps you solve a wide range of optimization problems on arrays. It’s not just about this one problemβ€”it’s about understanding how and when to apply the technique.

Keep practicing, and soon these patterns will come naturally. πŸ’ͺ
Happy coding! πŸš€

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *