← All lessonsUnit 3 · Pointers
Lesson 3.1

Two lists at once

One index for each list, moved by the rule of the problem, and when one list runs out, what is left of the other still has to be dealt with.

Reach for it when
Two inputs are read side by side.
The move
One index each. Every step moves one of them or both. When one list runs out, deal with what's left of the other.
Cost
O(n + m) time.

The idea

Harper

I shuffled two decks of cards together last night, the way a croupier does, and half of one deck vanished.

Arthur

Cards don't vanish. We'll find them. How does the shuffle go?

Harper

One pile in each hand. My thumbs let a card fall from the left, then one from the right, then the left again.

Arthur

Two piles, and a thumb on each. Each thumb knows where it is in its own pile.

Harper

In code that's an index for each array?

Arthur

i for the first, j for the second. One index can't do it, because the two piles move separately. Sometimes both thumbs let go, sometimes only one.

Harper

When do they stop?

Arthur

When one pile is empty. You can't take turns with nobody.

Harper

And then?

Arthur

Then the other pile still has cards in it. You drop them on top, all at once.

Harper

Merging two sorted piles is the same?

Arthur

The same thumbs. Only the rule changes: instead of taking turns, you let go of whichever card is smaller. The pile that loses a card moves on, and the other waits.

Harper

And when one sorted pile runs out?

Arthur

The same as the shuffle. What's left of the other drops on top. It's sorted already, and every card in it is bigger than anything you've put down.

Harper

I may have skipped that part.

Arthur

Then I know where your cards are.

That is the tool. You keep one index for each list. Each step looks at what the two indexes point at, takes something, and moves one index or both. When either list runs out, the shared walk ends, and whatever is left of the other list is dealt with on its own.

The shape

This is what you know by heart: two sorted arrays merged into one sorted array.

Swift
/// Two sorted arrays merged into one sorted array.
func merged(_ a: [Int], _ b: [Int]) -> [Int] {
    var i = 0                                    // a's finger
    var j = 0                                    // b's finger
    var result: [Int] = []
    while i < a.count && j < b.count {           // both still have something
        if a[i] <= b[j] {
            result.append(a[i])
            i += 1
        } else {
            result.append(b[j])
            j += 1
        }
    }
    while i < a.count {                          // what is left of a
        result.append(a[i])
        i += 1
    }
    while j < b.count {                          // what is left of b
        result.append(b[j])
        j += 1
    }
    return result
}

It has four parts, and each is there for a reason.

Watch it run

The arrays are a = [1, 4, 6] and b = [2, 3, 7, 8]. Each row is one number taken, with the two fingers after it.

takenijresult so far
1 from a10[1]
2 from b11[1, 2]
3 from b12[1, 2, 3]
4 from a22[1, 2, 3, 4]
6 from a32[1, 2, 3, 4, 6]
7, the rest of b33[1, 2, 3, 4, 6, 7]
8, the rest of b34[1, 2, 3, 4, 6, 7, 8]

The answer is [1, 2, 3, 4, 6, 7, 8]. Look at the fifth row: i reaches 3, which is a.count, so the shared walk ends there. The 7 and the 8 are still in b. The last two rows come from the loop for what is left of b. Without it, the answer would stop at the 6.

Step by step

Step 1

Are two arrays equal, element by element?

Swift
/// Whether two arrays hold the same numbers in the same order.
func sameElements(_ a: [Int], _ b: [Int]) -> Bool {
    if a.count != b.count {                      // different lengths can never match
        return false
    }
    for i in a.indices {                         // one index serves both
        if a[i] != b[i] {
            return false
        }
    }
    return true
}

What is new: reading two arrays at the same position. When the arrays have the same length, one index serves both: a[i] and b[i] are the elements side by side. So the first thing to settle is the length. Arrays of different lengths can never be equal, and a loop over a.indices would read past the end of a shorter b.

Step 2

Add two arrays of the same length, element by element

Swift
/// Each number of `a` added to the number at the same place in `b`.
/// The two arrays are the same length.
func added(_ a: [Int], _ b: [Int]) -> [Int] {
    var sums: [Int] = []
    for i in a.indices {
        sums.append(a[i] + b[i])
    }
    return sums
}

What is new: building a new array from the pair at each position. For 1, 2, 3 and 10, 20, 30 the answer is [11, 22, 33]. The problem promises the same length, so one index is still enough.

Step 3

Take turns: one from a, one from b, for arrays of the same length

Swift
/// One from `a`, then one from `b`, and so on. The two arrays are the same length.
func takingTurns(_ a: [Int], _ b: [Int]) -> [Int] {
    var result: [Int] = []
    for i in a.indices {
        result.append(a[i])                      // a's turn
        result.append(b[i])                      // then b's
    }
    return result
}

What is new: two appends for each position, in an order the problem fixes. First a's turn, then b's. For 1, 2, 3 and 7, 8, 9 the answer is [1, 7, 2, 8, 3, 9]. This is the shuffle with two piles of the same size, so both run out together.

Step 4

Walk two arrays of different lengths together and say which ran out first

Now the lengths differ, and one index is no longer enough: each array needs its own.

Swift
/// Walk both arrays together, a step at a time, until one runs out. Hand back what is
/// left of the other one: empty when they ran out together.
func whatIsLeft(_ a: [Int], _ b: [Int]) -> [Int] {
    var i = 0
    var j = 0
    while i < a.count && j < b.count {           // a step in both
        i += 1
        j += 1
    }
    var left: [Int] = []
    while i < a.count {                          // b ran out first
        left.append(a[i])
        i += 1
    }
    while j < b.count {                          // a ran out first
        left.append(b[j])
        j += 1
    }
    return left
}

What is new: the shared walk, while i < a.count && j < b.count, and what comes after it. The walk stops as soon as either finger reaches the end of its array. Then the array that did not run out still has something left, and the two loops after the walk collect it. Exactly one of them can find anything.

For 1, 2 against 5, 6, 7, 8, a runs out first, and what is left is [7, 8]. For 1, 2, 3 against 5 it is [2, 3], from a. Arrays of the same length run out together, and nothing is left.

The && matters. With || the walk would go on while either array had something, and read past the end of the other.

Step 5

Merge two sorted arrays into one sorted array

This step is the shape itself, written from an empty function.

What is new: the rule decides which finger moves. Taking turns moved both fingers every time. Merging moves only the finger whose number was taken, so the two fingers drift apart. That is fine: each still says where its own array has got to.

a[i] <= b[j] takes from a when the two are equal. Either is right for numbers, since equal numbers look the same. When the things being merged carry more than a number, <= keeps those from a ahead of equal ones from b.

Step 6

Does a begin with b?

Swift
/// Whether `a` begins with all of `b`.
func beginsWith(_ a: [Int], _ b: [Int]) -> Bool {
    var i = 0
    var j = 0
    while i < a.count && j < b.count {
        if a[i] != b[j] {
            return false
        }
        i += 1
        j += 1
    }
    return j == b.count                          // all of b was matched
}

What is new: the answer depends on which array ran out. The walk compares the two fingers and stops at the first difference. If it gets to the end of b, every element of b was matched, and a begins with it: true for 3, 1, 4, 1 and 3, 1. If it gets to the end of a first, b is longer than a, and part of b was never matched: false for 3, 1 and 3, 1, 4.

So the last line asks the right question: did b run out? j == b.count. An empty b runs out before it starts, and every array begins with nothing.

Merge Strings Alternately

Two words are given. Build a new word by taking a letter from the first, then a letter from the second, and so on. When one word runs out, the rest of the other goes on the end.

It is the shuffle, in letters. It comes in two small steps.

First, take turns from two words of the same length. This is step 3 on characters, by way of Array(s) and String(chars).

Swift
/// The letters of two words of the same length, taking turns:
/// "abc" and "xyz" give "axbycz".
func alternate(_ first: String, _ second: String) -> String {
    let a = Array(first)
    let b = Array(second)
    var result: [Character] = []
    for i in a.indices {
        result.append(a[i])
        result.append(b[i])
    }
    return String(result)
}

For "abc" and "xyz" it gives axbycz.

Next, take turns while both have some, then the rest. This is steps 3 and 4 together, on numbers first.

Swift
/// One from `a`, then one from `b`, while both have some.
/// Then the rest of the longer one.
func takingTurnsWithRest(_ a: [Int], _ b: [Int]) -> [Int] {
    var i = 0
    var j = 0
    var result: [Int] = []
    while i < a.count && j < b.count {
        result.append(a[i])
        result.append(b[j])
        i += 1
        j += 1
    }
    while i < a.count {
        result.append(a[i])
        i += 1
    }
    while j < b.count {
        result.append(b[j])
        j += 1
    }
    return result
}

For 1, 2 and 7, 8, 9, 10 it gives [1, 7, 2, 8, 9, 10]. Each turn moves both fingers, and the 9 and 10 come from the loop for what is left of b.

Then the problem itself. The same, on letters:

Swift
/// LeetCode 1768. The letters of two words taking turns,
/// then the rest of the longer word.
func mergeAlternately(_ word1: String, _ word2: String) -> String {
    let a = Array(word1)
    let b = Array(word2)
    var i = 0
    var j = 0
    var result: [Character] = []
    while i < a.count && j < b.count {
        result.append(a[i])
        result.append(b[j])
        i += 1
        j += 1
    }
    while i < a.count {
        result.append(a[i])
        i += 1
    }
    while j < b.count {
        result.append(b[j])
        j += 1
    }
    return String(result)
}

For "ab" and "pqrs" it gives apbqrs.

Is Subsequence

Two words are given, s and t. Can s be made from t by crossing letters out of t, without moving any? Then s is a subsequence of t: its letters appear in t in the same order, but not necessarily side by side.

First, is s at the very start of t? This is step 6 on letters.

Swift
/// Whether `t` begins with all of `s`.
func isAtStart(_ s: String, _ t: String) -> Bool {
    let small = Array(s)
    let big = Array(t)
    var i = 0
    while i < small.count && i < big.count {
        if small[i] != big[i] {
            return false
        }
        i += 1
    }
    return i == small.count
}

"ra" is at the start of "radar": true. Notice that here, as in step 6, the shorter word must run out, and both run out together when they match exactly.

Next, go through t once, moving on in s only on a match. Now the letters of s need not be side by side in t. So t's finger moves on every step, and s's finger moves only when the letter it points at is found. Count how many letters of s were found.

Swift
/// How many letters of `s`, from its start, can be found in `t` in order.
func matchedCount(_ s: String, _ t: String) -> Int {
    let small = Array(s)
    let big = Array(t)
    var i = 0                                    // the next letter of s to find
    var j = 0                                    // where we are in t
    while i < small.count && j < big.count {
        if small[i] == big[j] {
            i += 1                               // found: s moves on only on a match
        }
        j += 1                                   // t always moves on
    }
    return i
}

For "ace" in "abcde", all 3 letters are found: a, then c, then e. For "aec" only 2 are: after the e, there is no c left in t.

What is new: one finger that always moves, and one that moves only when its letter is found.

Then the problem itself. If s ran out, every letter was found in order:

Swift
/// LeetCode 392. Whether the letters of `s` appear in `t` in order,
/// not necessarily side by side.
func isSubsequence(_ s: String, _ t: String) -> Bool {
    let small = Array(s)
    let big = Array(t)
    var i = 0
    var j = 0
    while i < small.count && j < big.count {
        if small[i] == big[j] {
            i += 1
        }
        j += 1
    }
    return i == small.count                      // s ran out: every letter was found
}

"ace" in "abcde" is true, and "aec" is false. Each word is walked once. That is O(n + m), where n and m are the two lengths: the cost of every tool in this lesson.

What goes wrong

Forgetting what is left. The shared walk stops when either list runs out. Without the loops after it, the rest of the other list is lost: the lesson's merge would give [1, 2, 3, 4, 6], and the 7 and 8 would be gone.

Swift
func mergedForgettingTheRest(_ a: [Int], _ b: [Int]) -> [Int] {
    var i = 0
    var j = 0
    var result: [Int] = []
    while i < a.count && j < b.count {
        if a[i] <= b[j] {
            result.append(a[i])
            i += 1
        } else {
            result.append(b[j])
            j += 1
        }
    }
    return result                                // what is left of either is lost
}

One index for two lengths. One index is enough only when the problem promises the same length. Otherwise, a[i] and b[i] read past the end of the shorter array, and the program stops.

|| in the shared walk. while i < a.count || j < b.count goes on while either list has something, and then reads past the end of the other. The shared walk needs both: &&.

Asking the wrong list whether it ran out. "Does a begin with b?" is answered by b running out. "Is s a subsequence of t?" is answered by s running out. Ask which list must be used up, and test that one after the walk.

Say it back

1

Why does each list get its own index?

Show the answerHide the answer

Because the lists move separately. A step may take from one list and not the other, so each needs to remember where it has got to.

2

When does the shared walk stop, and what does && have to do with it?

Show the answerHide the answer

When either list runs out. && keeps the walk going only while both have something, so neither is read past its end.

3

After the shared walk, how many of the two loops for what is left can do anything?

Show the answerHide the answer

At most one. The walk stopped because one list ran out, and that list has nothing left.

4

In merging, which finger moves?

Show the answerHide the answer

Only the finger of the list whose number was taken. The other number has not been used yet.

5

In LeetCode 392, which finger always moves, and which moves only on a match?

Show the answerHide the answer

The finger in t always moves. The finger in s moves only when its letter is found.

6

Where did half of Harper's deck go?

Show the answerHide the answer

Her shuffle stopped when the first pile ran out, and she never dropped the rest of the other pile on top. The cards are still in her other hand. When one list runs out, deal with what is left of the other.

Practise

These are this lesson's problems in the Orithms app, in the order they come.

ProblemLevel
1Equal, element by elementEasy
2Add, element by elementEasy
3Take turnsEasy
4Which ran out, and what is leftEasy
5Merge two sorted arraysEasy
6Reading past the endEasy
7Does a begin with b?Easy
8Take turns with lettersEasy
9Take turns, then the restEasy
10Merge strings alternatelyEasy
11At the very startEasy
12How many letters are found in orderEasy
13Is subsequenceEasy

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.