Python 3D Academyবাংলা

The most water, and three-sum

🌍 In real life. On a flat roof, rainwater collects between two walls of different heights. However tall one wall is, the water can only rise as high as the shorter wall before it spills over. And the further apart the walls, the more water fits. Choosing the two walls that hold the most water means trading height against width, and a clever pair of pointers does it in one walk.

The problem. Given wall heights, pick two walls that hold the most water: min(h[L], h[R]) × (R − L).

The idea in one sentence: start with the widest pair, and always move the shorter wall inward, because keeping it can never do better.

Its words:

  • wall: one height h[i]; two walls hold water up to the shorter one
  • area: the width times the shorter height: (R - L) * min(h[L], h[R])
  • three-sum: finding every triple that adds up to 0; sort, fix one number, then run two pointers on the rest

How it works, step by step:

  1. L = 0, R = last; work out the water between them and remember the best
  2. if h[L] < h[R], move L right; otherwise move R left
  3. repeat until L meets R

Watch the water fill between the pointers, and the best so far climb to 49:

Why moving the shorter wall is safe. Say h[L] is the shorter one. Any other pair that keeps L uses a partner closer than R (less width), and its water can't be higher than h[L]. So every other pair with L holds at most what we just measured: L can be crossed off, exactly like a row in Lesson 2's grid. Moving the taller wall instead could skip the answer.

What it costs. One step per move, n − 1 moves: O(n), against n(n − 1)/2 pairs for trying them all: 36 pairs for these 9 walls, about 5 billion for 100,000.

Three-sum. Find every triple of numbers that adds up to 0, without repeats. Trying every triple is O(n³). Instead: sort, then for each number a, find pairs in the rest that add up to -a with Lesson 1's pair search. That is n walks of O(n): O(n²). To avoid repeated triples, skip a number equal to the one before it.

def three_sum(nums):
    nums = sorted(nums)
    found = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue                      # same a as before: skip
        l, r = i + 1, len(nums) - 1
        while l < r:
            s = nums[i] + nums[l] + nums[r]
            if s == 0:
                found.append([nums[i], nums[l], nums[r]])
                l += 1
                while l < r and nums[l] == nums[l - 1]:
                    l += 1                # skip repeats of b
            elif s < 0:
                l += 1
            else:
                r -= 1
    return found

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

Mistakes and edge cases.

  • moving the taller wall in the water problem can skip the best pair
  • for three-sum, forgetting to sort first breaks the pair search, and forgetting to skip equal numbers gives repeated triples like [-1, 0, 1] twice
  • after finding a triple, keep searching (move L on): there may be more with the same a
  • fewer than 2 walls hold no water, and fewer than 3 numbers have no triple: the loops simply don't run

Quiz

  1. How much water do walls of height 4 and 7, five places apart, hold? What does this print?

    print(min(4, 7) * 5)
  2. h[L] = 3 and h[R] = 8. Which pointer moves, and why?

    • L: every other pair with L is narrower and no higher than 3, so none can beat this one
    • R: the taller wall wastes space
    • Both, to save time
  3. What does this print?

    h = [2, 5, 4]
    l, r, best = 0, 2, 0
    while l < r:
        best = max(best, min(h[l], h[r]) * (r - l))
        if h[l] < h[r]:
            l += 1
        else:
            r -= 1
    print(best)
  4. Sort, then a two-pointer pair search for every first number: what does three-sum cost?

    • O(n²)
    • O(n³)
    • O(n)
  5. What does this print?

    nums = sorted([3, -2, -1, 1])
    print(nums, nums[0] + nums[1] + nums[3])
  6. max_water([1, 8, 6, 2, 5, 4, 8, 3, 7]) should be 49, but this answers 56, more than the walls can hold. Which line is wrong?

    def max_water(h):
        l, r = 0, len(h) - 1
        best = 0
        while l < r:
            area = (r - l) * max(h[l], h[r])
            best = max(best, area)
            if h[l] < h[r]:
                l += 1
            else:
                r -= 1
        return best

Coding tasks

  1. Write max_water(heights) in O(n) with two pointers: the most water two walls can hold, min(h[l], h[r]) * (r - l) (0 if there are fewer than 2 walls).

  2. Write three_sum(nums) in O(n²): every different triple of numbers that adds up to 0, each as a sorted list, the triples in sorted order. Sort first, then use a two-pointer search for each first number.