Walk an array once and edit it in place without losing data.
Use it when the task is to remove, filter or squeeze entries and keep their order, with no second array. Signal words: remove in place, keep the order, O(1) extra space, overwrite as you go.
Start read and write are both 0.
Step read visits each entry once. When the entry stays, copy it to write and move write on by one.
Stop when read has passed the last entry. The first write entries are the answer, so cut off the rest.
It does not fit an edit that makes the array longer. There, write from the back, or the write pointer runs ahead of read.
Cost: O(n) time, one read for each entry and at most one write for each kept entry, and O(1) extra space.
In this lesson you edit an array without a second one. You walk it once with two pointers, remove entries, reverse a range, and learn which edits must run from the back.
You work on the order sync of an online store. A packing tablet receives an array of order ids. Cancelled orders are marked with 0, and the list must keep the order of the others.
The tablet has memory for one array only, so the edit must happen in that array. A busy night sends 100,000 ids, and about 40,000 of them are cancelled. Moving one entry to the next slot takes about 2 nanoseconds.
Your team lead says: The sync must finish within a second. Remove the cancelled orders in place, and tell me how many ids are left.
Here is a short test: the ids 7, 0, 4, 0, 0, 9 and 3. After the edit the list reads 7, 4, 9 and 3.
So the task is this: remove every 0, keep the order of the rest, use no second array, and finish fast.
A packer checks a row of boxes on a shelf. One finger reads each box, from the left. A second finger marks the next free place at the left end of the row.
When the packer reads a box that stays, the box moves to the free place, and the second finger steps right. A box that is cancelled is skipped. At the end every place left of the second finger holds a kept box, in the original order.
Like a packer with two fingers: one reads every box from the left, the other marks the next free place, and kept boxes move there.
Before you write code, clean the seven ids by hand. It shows what each step must protect.
Solve it by hand: Seven orders: remove the cancelled ones in place. The hand-solve sheet loads in your browser.
You keep two places in mind: the entry you are reading, and the place where the next kept entry goes. They start together. The second place moves only when an entry is kept.
The ids are 7, 0, 4, 0, 0, 9 and 3. The target is 0.
| Read place | Entry | Action | Write after | List after |
|---|---|---|---|---|
| 0 | 7 | keep: copy to place 0 | 1 | [7, 0, 4, 0, 0, 9, 3] |
| 1 | 0 | skip | 1 | [7, 0, 4, 0, 0, 9, 3] |
| 2 | 4 | keep: copy to place 1 | 2 | [7, 4, 4, 0, 0, 9, 3] |
| 3 | 0 | skip | 2 | [7, 4, 4, 0, 0, 9, 3] |
| 4 | 0 | skip | 2 | [7, 4, 4, 0, 0, 9, 3] |
| 5 | 9 | keep: copy to place 2 | 3 | [7, 4, 9, 0, 0, 9, 3] |
| 6 | 3 | keep: copy to place 3 | 4 | [7, 4, 9, 3, 0, 9, 3] |
The first 4 entries, 7, 4, 9 and 3, are the answer. The entries after them are old copies, and they are ignored.
Start with a correct version. It finds each 0 and deletes it by shifting the rest of the list left, as in the first lesson.
def remove_zeros(values):
items = list(values)
i = 0
while i < len(items):
if items[i] == 0:
for j in range(i, len(items) - 1): # shift the tail left
items[j] = items[j + 1]
items.pop()
else:
i += 1
return itemsThis is correct. On the test list it makes 10 moves, which is fine for 7 entries.
Now check the real size.
A busy night has 100,000 ids. A seeded run has 40,014 cancelled ids. A move takes 2 nanoseconds.
Here is the count from running the code:
So the sync takes about four times the one second it has.
Predict the cost
Q Each deletion shifts the entries after the deleted one. Why is the total so large for 40,014 deletions in 100,000 entries?
Answer: B
A deletion at place i moves all the entries after i. Averaged over the list that is about half of it, so 40,014 deletions make billions of moves.
The first attempt is correct, but it pays for the whole tail again and again. Now look at what the cleaned list needs.
Look at the hand trace again. Each kept entry moved once, and only to a place at or before where it was. No entry had to wait while the others shifted.
So keep two pointers. read visits every entry in order. write is the place where the next kept entry goes. When read finds an entry to keep, copy it to write and move write on by one.
The key fact is that write is never ahead of read. A copy therefore writes over a place that read has already passed, and no unread entry is lost.
Here is the same list and the same sync, counted both ways:
| Method | Moves or reads | Writes |
|---|---|---|
| Delete one at a time | 2,005,197,272 moves | the moves are the writes |
| Read and write pass | 100,000 reads | 59,986 writes |
The pass costs about 160,000 steps, which is about 12,500 times fewer than the shifts. At 2 nanoseconds a step that is about 0.3 milliseconds.
Race: Removing cancelled orders: one at a time against one pass. The operation counter loads in your browser.
At 1,000 entries, deleting one at a time moves 206,181 entries and the pass reads 1,000. At 10,000 entries the counts are 20,275,690 against 10,000.
Read visits every entry once, and write marks the next place of the answer; a kept entry is copied from read to write, and write moves on.
The ids are [3, 0, 8, 0, 0, 5, 2, 0, 6]. The player stops at five steps and asks you to predict write.
Dry run: Predict each step: nine orders. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Read place | Entry | Action | Write after | List after |
|---|---|---|---|---|
| 0 | 3 | keep | 1 | [3, 0, 8, 0, 0, 5, 2, 0, 6] |
| 2 | 8 | keep: copy to place 1 | 2 | [3, 8, 8, 0, 0, 5, 2, 0, 6] |
| 5 | 5 | keep: copy to place 2 | 3 | [3, 8, 5, 0, 0, 5, 2, 0, 6] |
| 6 | 2 | keep: copy to place 3 | 4 | [3, 8, 5, 2, 0, 5, 2, 0, 6] |
| 8 | 6 | keep: copy to place 4 | 5 | [3, 8, 5, 2, 6, 5, 2, 0, 6] |
The places 1, 3, 4 and 7 hold 0, so they are skipped and are not shown. The answer is the first 5 entries: 3, 8, 5, 2 and 6. Look at the last list: the entries after place 4 are stale, which is why the code cuts them off.
The same idea works for reversing. Put one pointer at each end of the range, swap the two entries, and move both pointers in. When they meet, every entry has its final place.
Dry run: Six values reversed from both ends. The step-by-step player loads in your browser.
The run reverses six values in three swaps, which is n / 2. Nothing is copied to a second array, so the extra space is O(1).
A rotation moves the last k entries to the front. Reverse the whole range, then reverse the first k entries, then reverse the rest. For [1, 2, 3, 4, 5, 6, 7] and k = 3 the three reversals give [7, 6, 5, 4, 3, 2, 1], then [5, 6, 7, 4, 3, 2, 1], then [5, 6, 7, 1, 2, 3, 4]. That is 6 swaps in all.
Exercise · Predict the output: What the array holds after the pass. The read and write pass runs without cutting the tail. What does this print: write, then every entry of the array?
items = [2, 0, 0, 5, 0, 6, 7]
write = 0
for read in range(len(items)):
if items[read] != 0:
items[write] = items[read]
write += 1
print(write, *items)Here is the rule that keeps an in-place edit correct. Every line of both templates exists to protect it.
The entries before write are the answer so far, in order; read never falls behind write, so nothing is overwritten before it is read.
At the start both pointers are 0 and the answer is empty. Each step reads one entry and either keeps it or skips it. A kept entry goes to the place that write names, which read has already passed.
When read reaches the end, the first write entries are the answer. The same reasoning covers reversal: the entries outside the two pointers are already in their final places.
Use it when the task is to remove, filter or squeeze entries and keep their order, with no second array. Signal words: remove in place, keep the order, O(1) extra space, overwrite as you go.
Start: read and write are both 0.
Step: read visits each entry once. When the entry stays, copy it to write and move write on by one.
Stop: when read has passed the last entry. The first write entries are the answer, so cut off the rest.
It does not fit an edit that makes the array longer. There, write from the back, or the write pointer runs ahead of read.
Cost: O(n) time, one read for each entry and at most one write for each kept entry, and O(1) extra space.
def remove_value(values, target):
# [1] Work on a copy; write is the place for the next kept entry.
items = list(values)
write = 0
# [2] Read every entry once, from the front.
for read in range(len(items)):
# [3] Keep the entry unless it is the target: copy it to the write place and move the write place on.
if items[read] != target:
items[write] = items[read]
write += 1
# [4] The first write entries are the answer; cut off the rest.
return items[:write]public int[] removeValue(int[] values, int target) {
// [1] Work on a copy; write is the place for the next kept entry.
int[] items = values.clone();
int write = 0;
// [2] Read every entry once, from the front.
for (int read = 0; read < items.length; read++) {
// [3] Keep the entry unless it is the target: copy it to the write place and move the write place on.
if (items[read] != target) {
items[write] = items[read];
write++;
}
}
// [4] The first write entries are the answer; cut off the rest.
return java.util.Arrays.copyOf(items, write);
}vector<int> removeValue(vector<int>& values, int target) {
// [1] Work on a copy; write is the place for the next kept entry.
vector<int> items = values;
int write = 0;
// [2] Read every entry once, from the front.
for (int read = 0; read < (int)items.size(); read++) {
// [3] Keep the entry unless it is the target: copy it to the write place and move the write place on.
if (items[read] != target) {
items[write] = items[read];
write++;
}
}
// [4] The first write entries are the answer; cut off the rest.
items.resize(write);
return items;
}function removeValue(values, target) {
// [1] Work on a copy; write is the place for the next kept entry.
const items = [...values];
let write = 0;
// [2] Read every entry once, from the front.
for (let read = 0; read < items.length; read++) {
// [3] Keep the entry unless it is the target: copy it to the write place and move the write place on.
if (items[read] !== target) {
items[write] = items[read];
write++;
}
}
// [4] The first write entries are the answer; cut off the rest.
return items.slice(0, write);
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The kept order that is never kept. This code removes every target from the array in place, but it returns the wrong entries. Which line is wrong?
def remove_value(values, target):
items = list(values)
write = 0
for read in range(len(items)):
if items[read] != target:
items[read] = items[write]
write += 1
return items[:write]def reverse_in_place(values):
# [1] Work on a copy; one pointer at each end.
items = list(values)
left = 0
right = len(items) - 1
# [2] While the pointers have not met, swap the two entries.
while left < right:
items[left], items[right] = items[right], items[left]
# [3] Move both pointers one step towards the middle.
left += 1
right -= 1
# [4] Return the reversed list.
return itemspublic int[] reverseInPlace(int[] values) {
// [1] Work on a copy; one pointer at each end.
int[] items = values.clone();
int left = 0;
int right = items.length - 1;
// [2] While the pointers have not met, swap the two entries.
while (left < right) {
int tmp = items[left];
items[left] = items[right];
items[right] = tmp;
// [3] Move both pointers one step towards the middle.
left++;
right--;
}
// [4] Return the reversed list.
return items;
}vector<int> reverseInPlace(vector<int>& values) {
// [1] Work on a copy; one pointer at each end.
vector<int> items = values;
int left = 0;
int right = (int)items.size() - 1;
// [2] While the pointers have not met, swap the two entries.
while (left < right) {
swap(items[left], items[right]);
// [3] Move both pointers one step towards the middle.
left++;
right--;
}
// [4] Return the reversed list.
return items;
}function reverseInPlace(values) {
// [1] Work on a copy; one pointer at each end.
const items = [...values];
let left = 0;
let right = items.length - 1;
// [2] While the pointers have not met, swap the two entries.
while (left < right) {
[items[left], items[right]] = [items[right], items[left]];
// [3] Move both pointers one step towards the middle.
left++;
right--;
}
// [4] Return the reversed list.
return items;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Put it in order: Swap the two ends. Arrange the lines into a function that reverses the array by swapping the two ends and moving inwards.
def reverse_in_place(values):
items = list(values)
left, right = 0, len(items) - 1
while left < right:
items[left], items[right] = items[right], items[left]
left += 1
right -= 1
return items
left, right = 0, len(items)
items[left] = items[right]To reverse in place, put one pointer at each end, swap the two entries, and move both pointers inwards until they meet.
The two templates answer two kinds of question. You can pick before you write any code.
Then check the ends: what do the templates do on an empty array, on an array with nothing to remove, and on an array of one entry?
| Situation | Method | Why |
|---|---|---|
| Remove entries, keep the order | Read and write pass | One read each, writes only for kept entries |
| Flip a range | Two pointers from the ends | n / 2 swaps |
| Rotate by k | Three reversals | No second array |
| Make room for extra entries | Write from the back | The write place is ahead of the read place |
A shop app shows 7 banners in a carousel: 1, 2, 3, 4, 5, 6 and 7. The carousel moves right by 3 places, so the last 3 banners come first.
Use the reverse template on three ranges.
| Step | Range reversed | List after |
|---|---|---|
| 1 | all 7 places | [7, 6, 5, 4, 3, 2, 1] |
| 2 | the first 3 places | [5, 6, 7, 4, 3, 2, 1] |
| 3 | the last 4 places | [5, 6, 7, 1, 2, 3, 4] |
The carousel reads 5, 6, 7, 1, 2, 3 and 4, after 6 swaps and no second array.
Real data brings edge cases.
For values = [], the loop does not run, write stays 0, and the result is []. For reversal, right is -1, so left < right is false and nothing is swapped.
For values = [1, 2, 3] and target = 0, every entry is kept, and each is copied onto itself. write ends at 3, and the whole list is returned unchanged.
For values = [0, 0, 0], every entry is skipped. write stays 0, so the cut returns []. The array still holds the old entries, and they are not part of the answer.
For values = [1, 2, 3], the pointers swap places 0 and 2, then both move: left is 1 and right is 1. They have met, so the middle entry stays. The result is [3, 2, 1].
Exercise · Break it: The reversal that undoes itself. This code swaps each place with its mirror place, for every place in the array. Find an array where it gives the wrong answer.
def reverse_in_place(values):
items = list(values)
n = len(items)
for i in range(n):
items[i], items[n - 1 - i] = items[n - 1 - i], items[i]
return itemsThis version loops over the indexes and deletes each 0 with del items[i]. After a deletion the next entry slides into place i, and the loop moves on to i + 1, so it never looks at that entry.
Counterexample: values = [0, 0, 5]. The version returns [0, 5], because the second 0 slides into place 0 and is skipped. The read and write pass returns [5].
Do not change the length of a list while you loop over its indexes. Copy kept entries forward instead.
This version returns the whole array after the pass. The entries after write are old copies.
Counterexample: for [7, 0, 4, 0, 0, 9, 3] the array after the pass is [7, 4, 9, 3, 0, 9, 3]. The answer is only its first 4 entries, [7, 4, 9, 3].
Return items[:write], or return write as the new length.
After the pass, the entries after write are stale copies, so returning the whole array gives seven, four, nine, three, zero, nine, three.
This version swaps with items[left] = items[right] and then items[right] = items[left]. The second line copies the value that was written a moment ago, so one value is lost.
Counterexample: [1, 2, 3, 4] becomes [4, 3, 3, 4]. The correct result is [4, 3, 2, 1].
Hold one value in a temporary, or use a language swap that does it for you.
This version doubles each 0 in place, reading and writing from the front. When an entry is doubled, write runs ahead of read, and the next writes overwrite entries that were not read yet.
Counterexample: [1, 0, 2, 3], with the list kept at the same length. The version returns [1, 0, 0, 0], because the 2 is overwritten before it is read. The correct result is [1, 0, 0, 2].
An edit that makes the array longer must write from the back.
The sync must also write an audit file of the cancelled orders from the original list. An in-place pass overwrites some of them, so the cancelled entries are lost.
Copy the cancelled ids first, or work on a copy of the list. In-place is a choice for when memory is short and the old list is not needed.
Your team lead brings four product changes. Each one asks which pointer moves.
A list of timestamps has repeats side by side, and only the first of each run must stay. Copy an entry only when it differs from the last kept entry, items[write - 1]. This is LeetCode 26: Remove Duplicates from Sorted Array.
Every empty slot in a fixed-size buffer must be doubled, and the buffer must keep its length. Count the empty slots first, then read from the back and write from the back, so each entry lands in a place that has been read.
Find the next larger arrangement of a queue in place. Find the last place where the order rises, swap it with the next larger entry from the right, and reverse everything after it. That is LeetCode 31: Next Permutation.
Every guest moves to the seat that a list names, and the move repeats for many rounds. Follow the list from a seat and you come back to it: the seats form cycles. A guest on a cycle of length L is home again after L rounds.
So walk each cycle once and move each guest rounds mod L steps along it. For moves = [1, 2, 0, 4, 3] and 1,000,000 rounds, the cycle 0, 1, 2 shifts by 1 and the cycle 3, 4 by 0. The answer is [1, 2, 0, 3, 4], the same as a run of all 1,000,000 rounds.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you remove entries from an array in place and keep the order. Then say what it costs, and what you must do after the pass. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
I walk the array once with a read pointer, and keep a write pointer for the next place of the answer. An entry that stays is copied from read to write, and write moves on.
Write never passes read, so nothing is overwritten before it is read. The pass costs one read for each entry, which is O of n, with no second array.
After the pass the first write entries are the answer, so I cut off the rest or return write as the new length.
To remove entries in place and keep the order, I use two pointers moving forward. Read visits every entry once. Write marks the next place of the answer.
When read finds an entry to keep, I copy it to write and move write on. Write never gets ahead of read, so no unread entry is overwritten. At the end the first write entries are the answer, and I cut the array there.
That costs one read for each entry and one write for each kept entry: O of n time and O of 1 extra space. Deleting one entry at a time would shift the tail for every removal, which is billions of moves on a long list.
To reverse a range I put one pointer at each end, swap, and move inwards, which is n over 2 swaps. If an edit makes the array longer, I write from the back.
Checkpoint · Read and write pointers
Q1/3 In an in-place removal, what do the read and write pointers mean?
Answer: B
Read scans the whole array. Write marks where the next kept entry goes, so the first write entries are the answer so far.
Q2/3 Why is it safe to copy a kept entry to the write place while the pass is still running?
Answer: C
Write only moves when an entry is kept, and read moves for every entry. So write stays at or behind read, and the place it names has been passed.
Q3/3 The pass over [7, 0, 4, 0, 0, 9, 3] with target 0 has finished. What does the whole array hold?
Answer: C
The kept entries are copied forward, and the entries after write are not cleared. The answer is the first 4 entries, so you cut the array there.
Checkpoint · Costs
Q1/4 What does one read and write pass cost on n entries?
Answer: B
The pass visits each entry once and writes at most once for each. Extra space is O(1), but the time is O(n).
Q2/4 Deleting each cancelled order by shifting the tail left costs 2,005,197,272 moves for 100,000 entries with 40,014 cancelled. What makes it so costly?
Answer: C
A deletion at place i moves all the entries after i. Repeating it for 40,014 cancelled entries adds up to billions of moves.
Q3/4 An array holds 100,000 entries. How many entries move when you delete the entry at index 0 by shifting the rest left?
Answer: B
From the first lesson: the slots are contiguous, so a delete at index i of n entries moves n - 1 - i entries. At the front that is 99,999, which is why one pass beats deleting one at a time.
Q4/4 How many swaps does an in-place reversal of 100,000 entries make?
Answer: C
Each swap fixes two entries, one at each end, so n / 2 swaps are enough: 50,000 for 100,000 entries.
Checkpoint · Rotating and expanding
Q1/3 To rotate [1, 2, 3, 4, 5, 6, 7] right by 3, which reversals do you make?
Answer: B
Reversing all puts the last 3 entries first, but backwards. Reversing the first 3 and then the last 4 puts each part back in order: [5, 6, 7, 1, 2, 3, 4].
Q2/3 An edit doubles every 0 in an array of fixed length, in place. Why must it write from the back?
Answer: C
Each doubled 0 makes write move ahead of read. A forward pass then overwrites unread entries: [1, 0, 2, 3] becomes [1, 0, 0, 0] instead of [1, 0, 0, 2].
Q3/3 A loop uses del items[i] to remove each 0 from [0, 0, 5]. What does it return?
Answer: B
After the first deletion the second 0 slides into place 0, and the loop moves on to place 1, so it never looks at it. The read and write pass returns [5].
Ten questions on this lesson and the array costs of the first one. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Reverse each shipping batch | Freight | Easy | Two pointers inside each block |
| 2 | Apply the seat permutation | Stream | Easy | Following each cycle once, however many rounds |
| 3 | Next arrangement of a queue | Pay | Medium | Swap, then reverse the tail |
| 4 | Insert zeros after every blank | Chat | Medium | Write from the back |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.