Learn to THINK. Learn to CODE — Day 03: Two Pointers

So far we solved problems where we scanned a list of items, and used simple tools to remember what we had seen.

But think about it.
If a list has 100 items, do you want to go through it one by one?

Until now we used one pointer to move through the list. To read n items, it takes n steps.
What if you use two pointers instead? You can often read the list faster and make better decisions along the way.

That is the technique we are learning today. Two pointers.

Here is a simple way to feel the idea.

Imagine you have one task, and you split it between 2 engineers.
One engineer is doing very well. The other is not.
Which side do you push a little more?

You push the side that is limiting the progress. Correct.

Two pointers works the same way.
You start with two pointers, left and right.
Whichever side is limiting the result, you move that side.

Keep our rule in mind the whole time:

  1. Understand the problem clearly.
  2. Break it into small parts.
  3. Work through one small example by hand.
  4. Turn that thinking into simple steps.

Problem 1 — Container With Most Water

You are given an integer array height of length n. There are n vertical lines. The two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that, together with the x-axis, form a container that holds the most water.
Return the maximum amount of water the container can store.

Link: https://leetcode.com/problems/container-with-most-water/description/

 class Solution:

def maxArea(self, height: List[int]) -> int:
        left = 0
        right = len(height) - 1
        capacity = 0
        maxwater = 0

        while left < right:
            # Follow the rule. Check which side is limiting, then move that side.
            # The water is limited by the shorter line, so that side is the weak one.
            if height[left] < height[right]:
                # The left line is shorter, so it decides how much water we hold.
                capacity = (right - left) * height[left]
                # Move the weaker side, hoping to find a taller line.
                left = left + 1
            else:
                # The right line is shorter or equal, so it decides the water.
                capacity = (right - left) * height[right]
                right = right - 1

            # Always calculate the value at this point and compare it.
            if capacity > maxwater:
                maxwater = capacity

        return maxwater

Read the steps and the comments to see how we applied our rule to solve this.

Problem 2 — Trapping Rain Water (try this on your own)

Now try this one yourself.
Spend at least 2 hours on it before you look at the solution below. The struggle is where the thinking grows.

Link: https://leetcode.com/problems/trapping-rain-water/description/

 

 class Solution:

    def trap(self, height: List[int]) -> int:
        left = 0
        right = len(height) - 1
        left_max = 0
        right_max = 0
        total_water = 0

        while left < right:
            # Same idea. The shorter side decides the water, so we move that side.
            if height[left] < height[right]:
                # If this line is the tallest we have seen on the left, it becomes the new wall.
                if height[left] >= left_max:
                    left_max = height[left]
                else:
                    # Otherwise water sits on top, up to the wall height on the left.
                    total_water += left_max - height[left]
                left += 1
            else:
                # Mirror the same logic on the right side.
                if height[right] >= right_max:
                    right_max = height[right]
                else:
                    total_water += right_max - height[right]
                right -= 1

        return total_water

This is not really about coding. It is about Thinking.

 

Comments

Popular posts from this blog

Zillow Data Exporter

Learn to Think. Learn to Code : 01