Read and write
One index reads every element, another marks where the next kept element goes, and the array is changed in place with nothing new made.
- Reach for it when
- The problem says in place, remove, move to the end, or no extra array.
- The move
readvisits every element.writemarks where the next kept element goes.writenever gets ahead ofread.- Cost
- O(n) time, O(1) extra space.
The idea
I removed every 3 from an array, in place, the way the problem asked. The array is still five long, and two 3s are still in it.
Then you may have done it right. We'll look. What does "in place" mean to you?
No new array. Change the one I was given.
And an array can't get shorter in the middle without everything after the gap moving. So instead of cutting things out, you slide the keepers to the front.
How?
Two fingers again, but both start at the front. read looks at every number, one after another. write points at the place where the next number you keep should go.
And when read finds a keeper?
Copy it to where write points, and move write on. When it finds one to drop, do nothing. read moves on either way.
Can write get ahead of read?
Never. write only moves when something is kept, and every kept number has already been read. So you only ever write over a place you've finished reading.
And at the end?
The keepers are at the front, in their order, and write is how many there are. That number is the answer. Whatever is after it is left over from before.
Like my two 3s.
Like your two 3s. Nobody reads past the count you hand back.
That is the tool. read visits every element once. write marks where the next kept element goes, and moves only when something is kept, so it never gets ahead of read. The kept elements end up at the front in their order, write is how many there are, and what lies after them does not matter. One pass, and no array is made: O(n) time and O(1) extra memory.
The shape
This is what you know by heart: keep the numbers that aren't zero.
/// Keeps the numbers that aren't zero at the front of `numbers`, in order, and hands
/// back how many there are. What is after them is left over.
func keepNonZero(_ numbers: inout [Int]) -> Int {
var write = 0 // where the next kept number goes
for read in numbers.indices { // every number is read once
if numbers[read] != 0 { // this one is kept
numbers[write] = numbers[read]
write += 1
}
}
return write // how many were kept
}It has four parts, and each is there for a reason.
writestarts at 0. Nothing has been kept yet, so the first keeper goes to the front.readvisits everything.for read in numbers.indiceslooks at every number exactly once.- Keep: copy, then move
write.numbers[write] = numbers[read]puts the keeper in the next free place at the front. When nothing has been dropped yet,writeandreadare the same, and the number is copied onto itself, which does no harm. - The count is the answer.
writeends as the number of keepers. The array is still as long as it was, and after the keepers it holds whatever was there.
Watch it run
The array is [0, 1, 0, 3, 12]. Each row is one number read, and the array after it.
| read | the number | kept? | write after | the array after |
|---|---|---|---|---|
| 0 | 0 | no | 0 | [0, 1, 0, 3, 12] |
| 1 | 1 | yes | 1 | [1, 1, 0, 3, 12] |
| 2 | 0 | no | 1 | [1, 1, 0, 3, 12] |
| 3 | 3 | yes | 2 | [1, 3, 0, 3, 12] |
| 4 | 12 | yes | 3 | [1, 3, 12, 3, 12] |
The answer is 3, and the array is [1, 3, 12, 3, 12]. The first three places hold 1, 3 and 12, in their order. The last two still hold the 3 and the 12 from before. They are left over, and the count says not to read them. Look at the second row too: the 1 was copied from place 1 to place 0, and its old copy stays in place 1 until the 3 is written over it.
Step by step
Copy the numbers that aren't zero into a new array
The easy version first, with a new array.
/// The numbers that aren't zero, in order, in a new array.
func nonZero(_ numbers: [Int]) -> [Int] {
var kept: [Int] = []
for number in numbers {
if number != 0 {
kept.append(number)
}
}
return kept
}What is new: nothing yet, and that is the point. This is the job the shape does. It gives [1, 3, 12]. The shape does the same thing without making kept: the front of the array it was given becomes kept.
The same into the same array with a write index
This step is the shape itself, written from an empty function.
What is new: the array is the result. kept.append(number) becomes numbers[write] = numbers[read] and write += 1. The array is passed inout, so the caller's array changes, and the function hands back how many numbers were kept.
Remove every copy of one value, in place
This is LeetCode 27.
/// LeetCode 27. Keeps every number that isn't `val` at the front of `nums`, and hands
/// back how many there are.
func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
var write = 0
for read in nums.indices {
if nums[read] != val {
nums[write] = nums[read]
write += 1
}
}
return write
}What is new: only the rule for keeping, != val. For 3, 2, 3, 3, 5 with 3 removed, the count is 2, and the array is [2, 5, 3, 3, 5]. That is Harper's array. Its first two places hold 2 and 5. Its last three still hold 3, 3 and 5, left over. LeetCode checks only the first two.
Remove the repeats from a sorted array, in place
This is LeetCode 26. The array is sorted, so equal numbers are side by side, and the job is to keep one of each.
/// LeetCode 26. Keeps one of each number of a sorted array at its front, in order, and
/// hands back how many there are.
func removeDuplicates(_ nums: inout [Int]) -> Int {
if nums.isEmpty {
return 0
}
var write = 1 // the first number is always kept
for read in 1..<nums.count {
if nums[read] != nums[write - 1] { // different from the last one kept
nums[write] = nums[read]
write += 1
}
}
return write
}What is new: the rule for keeping looks at what was kept last. A number is kept when it differs from the last number written, nums[write - 1]. The first number is always kept, so write starts at 1 and the loop at 1, and the empty array is answered first, because it has no first number.
For 1, 1, 2, 3, 3, 3 the count is 3, and the array is [1, 2, 3, 3, 3, 3]. Comparing with the last number kept, not with the number just before in the array, is what makes it safe: by the time read reaches a place, the places before it may already have been written over.
Bring every even number to the front with swaps, in one pass
Now nothing is removed. Every number stays, and the even ones come first.
/// Brings every even number to the front, in one pass, by swapping each into the next
/// place at the front.
func evensFirst(_ numbers: inout [Int]) {
var write = 0
for read in numbers.indices {
if numbers[read] % 2 == 0 {
numbers.swapAt(write, read) // swap, so that nothing is lost
write += 1
}
}
}What is new: swapping instead of copying. When read finds an even number, it swaps it with the number at write. The number that was at write is not lost: it goes to where the even number was. For 3, 8, 5, 6, 2, 7 the result is [8, 6, 2, 3, 5, 7]. The even numbers kept their order. The odd ones are all there, though not always in their old order.
Copying, as in the shape, would lose numbers:
func evensFirstByCopying(_ numbers: inout [Int]) {
var write = 0
for read in numbers.indices {
if numbers[read] % 2 == 0 {
numbers[write] = numbers[read] // copying, not swapping
write += 1
}
}
}It gives [8, 6, 2, 6, 2, 7]. The 3 and the 5 were written over, and the 6 and the 2 appear twice.
Move Zeroes
Move every 0 in an array to its end, keeping the other numbers in their order. Do it in place.
First, keep the numbers that aren't zero at the front. This is the shape, run on a copy so that the whole array can be seen afterwards, left-over places included.
/// The array after the numbers that aren't zero have been kept at its front, with what
/// is left over after them as it was left.
func keptAtFront(_ numbers: [Int]) -> [Int] {
var copy = numbers
var write = 0
for read in copy.indices {
if copy[read] != 0 {
copy[write] = copy[read]
write += 1
}
}
return copy
}For [0, 1, 0, 3, 12] it gives [1, 3, 12, 3, 12]: the three keepers, then what was left over.
Next, fill what is left with zeros. Everything from write to the end is left over. Here it is as its own small function, given where to start:
/// `numbers` with every place from `start` to the end set to 0.
func zeroedFrom(_ numbers: [Int], _ start: Int) -> [Int] {
var copy = numbers
for i in start..<copy.count {
copy[i] = 0
}
return copy
}Then the problem itself. The two together, on the array in place:
/// LeetCode 283. Moves every 0 to the end, keeping the other numbers in their order.
func moveZeroes(_ nums: inout [Int]) {
var write = 0
for read in nums.indices {
if nums[read] != 0 {
nums[write] = nums[read]
write += 1
}
}
for i in write..<nums.count { // what is left over becomes 0
nums[i] = 0
}
}The result is [1, 3, 12, 0, 0]. When nothing was dropped, write ends at nums.count, and the range write..<nums.count is empty, so the second loop does nothing.
String Compression
An array of characters is written in runs, as in "Runs". Compress it in place: each run becomes its letter, followed by its length when the length is more than 1. A length of 12 is written as two characters, 1 and 2. Hand back the new length.
It comes in four small steps.
First, each run as its letter and its length, in a new array. This is the jumping way from "Runs": the outer loop stands at the start of a run, and the inner loop walks to its end. Here every run is shorter than 10, so its length is one digit.
/// Each run of `chars` as its letter and its length, in a new array: "aaabb" gives
/// a, 3, b, 2. Every run is shorter than 10.
func runsWithLengths(_ chars: [Character]) -> [Character] {
var result: [Character] = []
var start = 0
while start < chars.count {
var end = start
while end < chars.count && chars[end] == chars[start] {
end += 1
}
result.append(chars[start])
result.append(Character(String(end - start))) // one digit: runs are short
start = end
}
return result
}"aaabb" gives a3b2.
Next, leave the length out when it is 1.
/// The same, with the length left out when it is 1: "aaab" gives a, 3, b.
func compressedCopy(_ chars: [Character]) -> [Character] {
var result: [Character] = []
var start = 0
while start < chars.count {
var end = start
while end < chars.count && chars[end] == chars[start] {
end += 1
}
result.append(chars[start])
if end - start > 1 {
result.append(Character(String(end - start)))
}
start = end
}
return result
}"aaab" gives a3b.
Next, a length written as characters. A length of 12 is not one character. String(12) is "12", and Array of it gives the characters, as "Characters as numbers" showed:
/// A length as the characters that write it: 12 gives 1, 2.
func lengthCharacters(_ length: Int) -> [Character] {
Array(String(length))
}12 gives ["1", "2"].
Next, write into the same array. Here the runs are short again, and the result goes to the front of the array itself, with a write index.
/// Writes the compressed runs into the front of `chars` itself, and hands back how many
/// characters that took. Every run is shorter than 10.
func compressShortRuns(_ chars: inout [Character]) -> Int {
var write = 0
var start = 0
while start < chars.count {
var end = start
while end < chars.count && chars[end] == chars[start] {
end += 1
}
chars[write] = chars[start]
write += 1
if end - start > 1 {
chars[write] = Character(String(end - start))
write += 1
}
start = end
}
return write
}"aabccc" becomes "a2bc3", and the count is 5.
Why is it safe to write into the array that is still being read? Each run is read to its end before anything of it is written. And a run never takes more room written than it took to begin with: one letter takes one place, a run of 2 to 9 takes two, and a run of 10 or more takes three or more places for at least ten letters. So write never passes the start of the run being read, and nothing is written over before it has been read.
Then the problem itself. The same, with the length's characters written one by one:
/// LeetCode 443. Writes each run of `chars` into its front as its letter and, when the
/// run is longer than 1, its length. Hands back how many characters that took.
func compress(_ chars: inout [Character]) -> Int {
var write = 0
var start = 0
while start < chars.count {
var end = start
while end < chars.count && chars[end] == chars[start] {
end += 1 // read the whole run first
}
chars[write] = chars[start] // then write its letter
write += 1
let length = end - start
if length > 1 {
for digit in String(length) { // 12 is written as 1, then 2
chars[write] = digit
write += 1
}
}
start = end
}
return write
}"abbbbbbbbbbbb", an a and twelve b's, becomes "ab12". The lesson's code compressed every word of one to nine letters made of a and b, 1022 words, both in place and into a new array, and the two agree on every one.
What goes wrong
Expecting the array to get shorter. In place, the array keeps its length. The answer is the count, and what lies after it is left over: Harper's array still ends in 3, 3, 5, and that is right.
Moving write on every number. write moves only when something is kept. Moved on every number, it is just read again, and nothing is removed.
Comparing with the wrong neighbour. In LeetCode 26, compare with the last number kept, nums[write - 1]. The number just before read may already have been written over.
Copying where a swap was needed. When every number must stay, as in step 5, copy loses the number at write: 3, 8, 5, 6, 2, 7 became [8, 6, 2, 6, 2, 7]. Swap.
Writing before reading. In LeetCode 443, read the whole run before writing any of it. Writing as you read would overwrite letters of the run you are still counting.
Say it back
What do read and write each mark?
Show the answerHide the answer
read is the element being looked at. write is where the next kept element goes.
Why can write never get ahead of read?
Show the answerHide the answer
write moves only when an element is kept, and every kept element has been read already.
What does the function hand back, and what about the places after it?
Show the answerHide the answer
How many elements were kept. The places after them are left over, and nobody reads them.
In LeetCode 26, which number is a new one compared with?
Show the answerHide the answer
The last number kept, nums[write - 1].
Why is it safe to compress LeetCode 443 in place?
Show the answerHide the answer
Each run is read before it is written, and a run never takes more room written than it took before. So write never passes what is still to be read.
Why are there still two 3s in Harper's array after she removed every 3?
Show the answerHide the answer
Removing in place doesn't make the array shorter. Her function slid the 2 and the 5 to the front and handed back 2. The 3, 3 and 5 after them are left over from before, and nobody reads past the count.
Practise
These are this lesson's problems in the Orithms app, in the order they come.
| Problem | Level | |
|---|---|---|
| 1 | The easy version | Easy |
| 2 | Keep them in place | Easy |
| 3 | Write moves every time | Easy |
| 4 | Remove every copy of one value | Easy |
| 5 | Remove the repeats from a sorted array | Easy |
| 6 | Evens to the front | Easy |
| 7 | Kept at the front | Easy |
| 8 | Fill the rest with zeros | Easy |
| 9 | Move zeroes | Easy |
| 10 | Each run with its length | Easy |
| 11 | Leave out the 1 | Easy |
| 12 | A length as characters | Easy |
| 13 | Short runs, in place | Medium |
| 14 | String compression | Medium |
These problems are done in the Orithms Mac app.
Every piece of code and every number in a lesson comes from a file that was compiled and run.