Eight problems that rewrite or compare sequences with pointers that only move on. The move: say what the region behind each pointer has settled, and never touch data still unread.
You work on the back end of a payments app, a warehouse system and an alerts service. The eight problems on this street come from all three. Each one rewrites a sequence or compares two of them, and each does it in a single walk, with no copy of the data.
What differs is what the pointers stand for. In some problems a read pointer finds values and a write pointer keeps them. In others there is a pointer on each of two inputs, or on each end of one input.
| Problem | The pointers | The region behind them has settled |
|---|---|---|
| Name typed on a sticky keyboard | i on the name, j on the typed text |
the name up to i is matched by the text up to j |
| Robots on a one-lane rail | i on the start rail, j on the target |
the robots before them are paired and legal |
| Slide a row of number tiles | read and write |
the cells before write are the finished row |
| Farthest pair across two falling lists | i on the first list, j on the second |
pairs that were rejected can never become valid |
| Largest charge with a matching refund | lo and hi on the sorted amounts |
amounts outside them have no partner |
| Strip every banned word | read and write |
the letters before write have no banned word left |
| Merge two sorted inventories in place | i, j and k from the back |
the slots after k hold the largest codes, in order |
| Interleave odds and evens | an even slot and an odd slot | the slots before each pointer are filled |
Read the last column. Every row says something is finished, and that is what lets a pointer move on without looking back.
Exercise · Predict the output: What is left of the alert?. The read pointer visits each letter once, and the write pointer decides what stays. The banned word is `abc`. What does the code print?
message = "aabcbcd"
word = "abc"
letters = list(message)
size = len(word)
write = 0
for read in range(len(letters)):
letters[write] = letters[read]
write += 1
if write >= size and "".join(letters[write - size:write]) == word:
write -= size
print("".join(letters[:write]))The move is three sentences you say before you write any code.
First, what has each pointer settled? Name the region behind it. Second, which pointer moves in each case, and what rule decides it?
Third, why can no unread value be overwritten or skipped? If you cannot answer that, the pointers are on the wrong ends.
Each pointer owns a finished region, every step grows one region by one position, and no step writes to a position that a pointer has yet to read.
In the prediction above, write never passed read, so the slot it wrote to had always been read already. That is why the text could be edited in the same array.
The invariant also tells you the cost. Each step moves a pointer on, so the walk takes at most as many steps as the pointers can travel. The write pointer steps back after a cut, but it can only step back over letters it wrote.
Take the message a repeated 20,000 times followed by b repeated 20,000 times, and the banned word ab. Cutting the leftmost copy and rebuilding the text each time copies 399,980,000 letters in all. The write pointer reads 40,000 letters and writes at most 40,000.
Fill the spare room from the back: the largest code goes into the last free slot, and no unread code is overwritten.
Exercise · Find the bug: A tile that merges twice. A swipe slides tiles left and merges two equal neighbours into one tile. A tile made by a merge must not merge again in the same swipe. Which line breaks that rule?
def slide_left(row):
write = 0
can_merge = False
for read in range(len(row)):
tile = row[read]
if tile == 0:
continue
if can_merge and row[write - 1] == tile:
row[write - 1] = tile * 2
can_merge = True
else:
row[write] = tile
write += 1
can_merge = True
for i in range(write, len(row)):
row[i] = 0
return rowThe Academy lessons Read and write pointers, Merging sorted sequences, Opposite ends and Three-way partition teach each pointer pattern alone. This street changes four things about them.
The write pointer can go back. In compaction it only moves on. When the banned word is cut, write steps back by the length of the word, so the letters that now touch are tested again. The written part behaves as a stack that lives inside the input.
A merge runs from the back when it fills spare room. The shelf [1, 3, 5, _, _] holds three codes, and the delivery is [2, 4]. Merging from the front writes 2 over the 3, and the shelf ends as [1, 2, 2, 2, 4].
From the back, the largest code goes into the last free slot, and the shelf becomes [1, 2, 3, 4, 5]. The free slots are always ahead of the unread codes.
Two pointers over two inputs follow a rule, not equality. A typed letter may repeat the one before it. A robot may move only one way. A balance never rises, so once the second list has fallen below the first, it stays below.
State the rule as the reason for each move, as you would for an interviewer.
A partition can use one write pointer per class. Three-way partition swaps values into place. When the classes must alternate, as even and odd ids do, each class gets its own write slot that steps by two.
One more case: after a sort, the two ends can be the pointers. The amounts -7, -3, 3, 7 have a refund at one end and a charge at the other. The larger absolute value has no partner among the smaller ones and moves in.
Exercise · Put it in order: Merge from the back. Arrange the lines into a merge of `extra` into the spare room at the end of `shelf`, which holds `m` codes. Fill the last free slot first.
def merge_inventory(shelf, m, extra):
i, j = m - 1, len(extra) - 1
k = len(shelf) - 1
while j >= 0:
if i >= 0 and shelf[i] > extra[j]:
shelf[k] = shelf[i]
i -= 1
else:
shelf[k] = extra[j]
j -= 1
k -= 1
return shelf
k = m - 1Merging into spare room from the front writes over codes that have not been read. Run it from the back.
Solve them in this order. The first four are single-purpose walks, the next two add a rule or a second write pointer, and the last two combine a rule with a changing region.
Before you code each problem, say the three sentences of the move aloud. Name what each pointer has settled, which pointer moves in each case, and why nothing unread is overwritten.
Give each problem about 20 minutes. Spend the first five minutes on the three sentences and on one small input that you walk by hand, writing down both pointers at every step.
Three cases come back on almost every rung. One input may be used up before the other, a write pointer may have nothing to write yet, and a cut may join two pieces. Write one small test for each.
When a solution fails, compare the pointers with your sentences. Most wrong answers come from a pointer that moves on a case you did not name, or from a write that reaches a position not yet read.
Checkpoint · In place and partitions
Q1/5 You merge a sorted delivery into the spare room at the end of a sorted shelf. From which end do you fill the shelf, and why?
Answer: B
The spare room is at the end of the shelf. Filling it from the back puts the largest code in a free slot, so no unread code is overwritten. From the front, the merge overwrites codes it has not read.
Q2/5 A write pointer cuts a banned word it has completed. Why does it step back by the length of the word?
Answer: C
A cut can join the letters on its two sides into a new copy of the word. Stepping write back puts those letters in the tail again, so the next check sees them.
Q3/5 The amounts are sorted: -9, -4, 2, 5, 7. The pointer lo is at -9 and hi is at 7. You look for a charge with an exact matching refund. Which pointer moves?
Answer: B
The refund of 9 would need a charge of 9, and the largest charge left is 7. So -9 has no partner and lo moves in.
Q4/5 A robot marked L can only move left. It sits at cell 5 of the start rail. At which cells of the target rail can the same robot end up?
Answer: C
A robot that only moves left can stay or end up at a lower cell. The check on each matched pair is that an L does not end to the right of its start.
Q5/5 The name is ab and the typed text is a. The walk reads the whole typed text without a failed step. What must the check do before it answers yes?
Answer: B
The typed text ran out, but the name still has its letter b. The answer is yes only when the name pointer has reached the end of the name too.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.