← All lessonsUnit 3 · Pointers
Lesson 3.3

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
read visits every element. write marks where the next kept element goes. write never gets ahead of read.
Cost
O(n) time, O(1) extra space.

The idea

Harper

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.

Arthur

Then you may have done it right. We'll look. What does "in place" mean to you?

Harper

No new array. Change the one I was given.

Arthur

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.

Harper

How?

Arthur

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.

Harper

And when read finds a keeper?

Arthur

Copy it to where write points, and move write on. When it finds one to drop, do nothing. read moves on either way.

Harper

Can write get ahead of read?

Arthur

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.

Harper

And at the end?

Arthur

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.

Harper

Like my two 3s.

Arthur

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.

Swift
/// 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.

Watch it run

The array is [0, 1, 0, 3, 12]. Each row is one number read, and the array after it.

readthe numberkept?write afterthe array after
00no0[0, 1, 0, 3, 12]
11yes1[1, 1, 0, 3, 12]
20no1[1, 1, 0, 3, 12]
33yes2[1, 3, 0, 3, 12]
412yes3[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

Step 1

Copy the numbers that aren't zero into a new array

The easy version first, with a new array.

Swift
/// 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.

Step 2

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.

Step 3

Remove every copy of one value, in place

This is LeetCode 27.

Swift
/// 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.

Step 4

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.

Swift
/// 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.

Step 5

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.

Swift
/// 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:

Swift
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.

Swift
/// 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:

Swift
/// `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:

Swift
/// 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.

Swift
/// 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.

Swift
/// 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:

Swift
/// 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.

Swift
/// 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:

Swift
/// 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

1

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.

2

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.

3

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.

4

In LeetCode 26, which number is a new one compared with?

Show the answerHide the answer

The last number kept, nums[write - 1].

5

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.

6

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.

ProblemLevel
1The easy versionEasy
2Keep them in placeEasy
3Write moves every timeEasy
4Remove every copy of one valueEasy
5Remove the repeats from a sorted arrayEasy
6Evens to the frontEasy
7Kept at the frontEasy
8Fill the rest with zerosEasy
9Move zeroesEasy
10Each run with its lengthEasy
11Leave out the 1Easy
12A length as charactersEasy
13Short runs, in placeMedium
14String compressionMedium

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.