• Interview Preparation
  • πŸš€ Code Day 4 – Two Pointers (Cracking Array Problems Efficiently)

    Welcome to Day 4 of your coding interview journey.

    So far, we’ve built a strong foundation:

    • βœ… Day 1: HashMaps
    • βœ… Day 2: Sliding Window
    • βœ… Day 3: Arrays

    Today, we unlock another powerful pattern:

    πŸ‘‰ Two Pointers

    This technique is essential for solving array and string problems efficiently β€” often reducing complexity from O(nΒ²) to O(n).


    🧠 What is the Two Pointers Technique?

    The idea is simple:

    πŸ‘‰ Use two indices (pointers) to iterate through the data, usually from different directions.

    Instead of nested loops, you:

    • Move pointers based on conditions
    • Narrow down the search space efficiently

    πŸ”‘ When Should You Use It?

    Look for these signals in problems:

    • Sorted arrays
    • Pairs or triplets
    • Target sums
    • Palindromes
    • Problems involving optimization (max/min)

    πŸ’‘ Problem 1 – Container With Most Water


    🧩 Problem

    Given an array height, where each element represents a vertical line:

    πŸ‘‰ Find two lines that together form a container that holds the maximum amount of water.


    ❌ Brute Force

    • Check all pairs
      πŸ‘‰ Time Complexity: O(nΒ²)

    βœ… Optimal Approach – Two Pointers

    We start with:

    • Left pointer at the beginning
    • Right pointer at the end

    Then:

    • Calculate area
    • Move the pointer with the smaller height

    πŸ› οΈ Solution in Python

    def max_area(height):
        left, right = 0, len(height) - 1
        max_water = 0
    
        while left < right:
            width = right - left
            h = min(height[left], height[right])
            max_water = max(max_water, width * h)
    
            # Move the smaller pointer
            if height[left] < height[right]:
                left += 1
            else:
                right -= 1
    
        return max_water
    

    βœ… Example

    height = [1,8,6,2,5,4,8,3,7]
    print(max_area(height))
    

    Output:

    49
    

    🎯 Key Insight

    πŸ‘‰ The limiting factor is always the shorter line

    So moving the taller line won’t help β€” only moving the shorter one might increase area.


    ⚑ Complexity

    • Time: O(n)
    • Space: O(1)

    πŸ’‘ Problem 2 – 3Sum


    🧩 Problem

    Given an array nums, return all unique triplets [a, b, c] such that:

    a + b + c = 0


    ❌ Brute Force

    • Try all triplets
      πŸ‘‰ Time Complexity: O(nΒ³)

    βœ… Optimal Approach – Sorting + Two Pointers

    Steps:

    1. Sort the array
    2. Fix one number
    3. Use two pointers to find the other two

    πŸ› οΈ Solution in Python

    def three_sum(nums):
        nums.sort()
        result = []
    
        for i in range(len(nums)):
            # Skip duplicates
            if i > 0 and nums[i] == nums[i - 1]:
                continue
    
            left, right = i + 1, len(nums) - 1
    
            while left < right:
                total = nums[i] + nums[left] + nums[right]
    
                if total == 0:
                    result.append([nums[i], nums[left], nums[right]])
    
                    # Skip duplicates
                    while left < right and nums[left] == nums[left + 1]:
                        left += 1
                    while left < right and nums[right] == nums[right - 1]:
                        right -= 1
    
                    left += 1
                    right -= 1
    
                elif total < 0:
                    left += 1
                else:
                    right -= 1
    
        return result
    

    βœ… Example

    nums = [-1,0,1,2,-1,-4]
    print(three_sum(nums))
    

    Output:

    [[-1, -1, 2], [-1, 0, 1]]
    

    🎯 Key Insights

    • Sorting enables efficient pointer movement
    • Avoid duplicates carefully
    • Reduce O(nΒ³) β†’ O(nΒ²)

    ⚠️ Common Mistakes

    • ❌ Forgetting to sort the array
    • ❌ Not handling duplicates
    • ❌ Moving both pointers incorrectly
    • ❌ Using brute force

    πŸ§ͺ Practice Problems

    To master Two Pointers, try:

    1. Two Sum II (sorted array)
    2. Valid palindrome
    3. Remove duplicates from sorted array
    4. 4Sum
    5. Trapping rain water

    🎯 Key Takeaways

    • Two Pointers reduces nested loops
    • Works best with:
      • Sorted arrays
      • Pair/triplet problems
    • Combine with:
      • Sorting
      • Greedy decisions

    πŸš€ Your Challenge (Day 4)

    Solve this:

    Given a sorted array, remove duplicates in-place and return the new length.


    πŸ“Œ Final Thoughts

    Two Pointers is one of the highest ROI patterns for interviews.

    Master it, and you’ll solve problems that many candidates struggle with.

    You’re already 4 days in β€” and building real momentum. πŸ’ͺ

    3 mins