Reef Pointer Pairs
A row of shells lies on the reef, sorted from lightest to heaviest. Two shells must weigh exactly 20 together to open the treasure clam. Use two pointers, one at each end, to find them fast.
๐ง Before we start
Stage Sliding Spotlight moved one frame along a list. Today two markers move toward each other. This is the two-pointer technique: on a sorted list, one pointer starts at each end, the program adds the two items, and then moves only the pointer that fixes the total. If the total is too small, the left pointer moves up. If it is too big, the right pointer moves down.
Set up the hunt
Tap the steps in the order a program uses them to start a two-pointer hunt.
Choose which pointer moves
Read the total, compare it with 20, and choose the pointer move that can still reach the target. Two rounds.
Catch the treasure pair
Run the hunt yourself. Each time, read the total and move the pointer that fixes it. Catch the pair when the total is exactly 20.
Count the saved work
Your hunt checked 7 totals. Trying every pair of 8 shells needs 28 checks. Now picture a reef with 20 shells. Pick the true comparison.
20 ร 19 รท 2 = ?
at most 20 โ 1 = ?
๐ What you learned
- Two pointers use two markers that move through a list together.
- The list must be sorted so a move has a predictable effect on the total.
- A total that is too small means the left pointer moves up to a heavier shell.
- A total that is too big means the right pointer moves down to a lighter shell.
- Each move rules out a shell for good, so no pair is checked twice.
- With 20 shells, two pointers need at most 19 checks instead of 190, and the saving grows with bigger lists.