Lesson 2 · Unit 01
Reader and writer
Clean up a list in place with a slow index and a fast one
What you practise
- Remove duplicates and move zeroes in place
Try a question from this lesson
Pick one
You remove duplicates from a sorted list of n items by deleting each one where it sits. Every deletion shifts all later items left. What is the worst-case cost?
Correct answer
O(n²)
Why
Deleting from the middle of an array shifts up to n items, and there can be close to n deletions: O(n²). The trick in this lesson is to overwrite instead of delete, which never shifts anything.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Reader and writer
Use two indexes that both move left to right. The reader visits every item. The writer w marks the slot where the next keeper goes.
Keepers are copied forward; nothing is deleted. When the reader is done, the first w slots hold the result, so the function returns w.
def dedupe(nums):
w = 0
for x in nums:
if w == 0 or x != nums[w - 1]:
nums[w] = x
w += 1
return w # the new lengthfunction dedupe(nums) {
let w = 0;
for (const x of nums) {
if (w === 0 || x !== nums[w - 1]) {
nums[w] = x;
w += 1;
}
}
return w; // the new length
}function dedupe(nums: number[]): number {
let w = 0;
for (const x of nums) {
if (w === 0 || x !== nums[w - 1]) {
nums[w] = x;
w += 1;
}
}
return w; // the new length
}Python noteWriting to nums[w] while looping over nums is safe here only because the writer never gets ahead of the reader.
TypeScript notenums: number[] is passed by reference, as in Python: the function changes the caller's array and returns only the count.
10 more exercises in the app
- 2× type the answer
- 3× multiple choice
- 2× fill the blanks
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.