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:
- Understand
the problem clearly.
- Break
it into small parts.
- Work
through one small example by hand.
- 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/
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/
This is not really about coding. It is about Thinking.
Comments
Post a Comment