← All lessonsUnit 2 · One pass, remembering something
Lesson 2.1

Best so far

One variable holds the best thing seen so far, and every element gets one chance to replace it.

Reach for it when
The problem says largest, smallest, highest, greatest or longest.
The move
One variable holds the best seen yet. Each element may replace it. Start it from the first element, not from zero.
Cost
O(n) time, O(1) extra space.

The idea

Harper

My friend Zero won a singing contest last night.

Arthur

Congratulations to Zero. Was Zero in it?

Harper

That's the awkward part. We'll come back to it. Here are five numbers: 3, 9, 4, 9, 1. Which is the largest?

Arthur

Nine.

Harper

How did you do that?

Arthur

I looked at them.

Harper

All at once. Here are a million numbers. Look at them.

Arthur

I'd rather not.

Harper

Then do it the way you'd have to with a million: one at a time, left to right. What do you have to remember as you go?

Arthur

Only the largest one I've met. Not the others. If the next number is bigger, I remember that one instead.

Harper

One thing to remember. Picture a single chair at the front of a room. Whoever is best so far sits in it. Each number walks up. Either it's better and takes the chair, or it isn't and walks on.

Arthur

And when the line is empty, whoever is in the chair is the answer.

Harper

Who sits in the chair before anyone has walked up?

Arthur

The first number. It's the best so far when it's the only one so far.

Harper

Not zero?

Arthur

Zero isn't one of the numbers. You'd be seating someone who never entered.

Harper

Hold that thought. It has a singing career.

That is the whole tool: one variable, one pass, and a start that is real. Everything else in this lesson is that idea with one thing changed at a time.

The shape

This is what you know by heart:

Swift
/// The largest number in `numbers`, which is never empty.
func largest(_ numbers: [Int]) -> Int {
    var best = numbers[0]            // start from something real: the first number
    for number in numbers {
        if number > best {           // a challenger
            best = number            // takes the chair
        }
    }
    return best                      // whoever is in the chair at the end
}

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

The loop also meets the first number again and compares it with itself. That does no harm, and it keeps the loop as plain as a loop can be.

For plain numbers Swift lets you write the challenge in one line:

Swift
func largestShort(_ numbers: [Int]) -> Int {
    var best = numbers[0]
    for number in numbers {
        best = max(best, number)
    }
    return best
}

Both are right. Learn the one with the if. When the thing in the chair is a position or a word, there is no max to call, and the if is still there.

Watch it run

The five numbers are 3, 9, 4, 9 and 1. Here is best before and after each one.

numberbest beforebigger?best after
33no3
93yes9
49no9
99no9
19no9

The answer is 9. Look at the fourth row. The second 9 does not take the chair, because it is not bigger than the 9 already sitting there. That one detail decides step 3.

Step by step

Step 1

The largest number in an array

This step is the shape itself, written from an empty function. What is new is everything: a variable that starts as numbers[0], a loop, and an if.

Say the sentence that stays true as the loop runs: best is the largest of the numbers met so far. It is true before the loop, because only the first number has been met. Each pass keeps it true. So it is true at the end, when every number has been met.

The problems promise that the array is never empty, so numbers[0] is always there.

Step 2

The smallest

One character changes.

Swift
/// The smallest number in `numbers`, which is never empty.
func smallest(_ numbers: [Int]) -> Int {
    var best = numbers[0]
    for number in numbers {
        if number < best {           // the only change: what "better" means
            best = number
        }
    }
    return best
}

What is new: the comparison is the only place that knows what "best" means. Turn > into < and the same chair holds the smallest. Nothing else moves, and the variable can still be called best.

Step 3

The position of the largest, the first one if there's a tie

Now the question is where, not what. So the chair holds a position.

Swift
/// Where the largest number is. When several are the largest, the first of them.
func positionOfLargest(_ numbers: [Int]) -> Int {
    var bestAt = 0                   // the chair now holds a position
    for i in numbers.indices {
        if numbers[i] > numbers[bestAt] {
            bestAt = i
        }
    }
    return bestAt
}

What is new: you keep bestAt, and you read the value through it with numbers[bestAt]. The loop goes over numbers.indices, because a position is what you need to keep.

The tie is settled by one character. With >, a later number has to be strictly bigger to take the chair, so of two equal largest numbers the first keeps it: for 3, 9, 4, 9, 1 the answer is 1. With >=, an equal number takes the chair too, so the last one wins: the answer would be 3. Neither is wrong in general. The problem says which it wants, and you choose the character.

Step 4

The longest word

Swift
/// The longest word. When several are the longest, the first of them.
/// `words` is never empty.
func longestWord(_ words: [String]) -> String {
    var best = words[0]
    for word in words {
        if word.count > best.count {     // compare the lengths
            best = word                  // keep the word
        }
    }
    return best
}

What is new: the thing you keep and the thing you compare are different. The chair holds the word. The comparison looks at count. For fig, banana, cherry and kiwi the answer is banana: cherry is just as long, and it came later, so with > it does not take the chair.

A common slip is to keep the length and lose the word. Ask what the problem wants back, and put that in the chair.

Step 5

The largest and the smallest in one pass

Swift
/// The smallest and the largest number, in that order, found in one pass.
func smallestAndLargest(_ numbers: [Int]) -> [Int] {
    var low = numbers[0]
    var high = numbers[0]
    for number in numbers {
        if number < low {
            low = number
        }
        if number > high {
            high = number
        }
    }
    return [low, high]
}

What is new: two chairs, one line of people. Each number is shown to both chairs. For 3, 9, 4, 9, 1 this gives [1, 9].

The two ifs are separate on purpose. In an array of one number, that number is both the smallest and the largest, and each chair must get to see it.

Step 6

How many numbers equal the largest?

You cannot count the largest numbers until you know what the largest is. So do the two jobs one after the other.

Swift
/// How many of the numbers are the largest one.
func countOfLargest(_ numbers: [Int]) -> Int {
    var best = numbers[0]
    for number in numbers {              // first pass: find it
        if number > best {
            best = number
        }
    }
    var count = 0
    for number in numbers {              // second pass: use it
        if number == best {
            count += 1
        }
    }
    return count
}

What is new: using the best after you have found it. For 3, 9, 4, 9, 1 the count is 2.

Two loops one after the other cost two passes, which is still a number of steps that grows in step with the array. A loop inside a loop would be a different matter. The last lesson of this unit, "How the work grows", comes back to that.

Step 7

The largest when every number is negative

Here is the largest number again, with one line changed.

Swift
func largestStartingFromZero(_ numbers: [Int]) -> Int {
    var best = 0                         // wrong: zero may not be in the array at all
    for number in numbers {
        if number > best {
            best = number
        }
    }
    return best
}

For 3, 9 and 4 it answers 9, and it looks fine. For -5, -2 and -9 it answers 0. The right answer is -2.

What is new: the start is part of the answer. Zero was put in the chair before anyone walked up, and nobody in the line could beat it. So the function handed back a number that was never in the array.

The fix is the first line of the shape: var best = numbers[0]. In this step's problem you are given the broken version and asked to mend it.

Kids With the Greatest Number of Candies

Each child has some candies, and there are some extra ones. For each child the question is: if this child got all of the extras, would they have at least as many as any other child?

It comes in three small steps, and you already have the first half of each.

First, a yes or no for every number. For each number, is it the largest? Find the largest once, then ask each number about it.

Swift
/// For each number, whether it is the largest.
func isLargest(_ numbers: [Int]) -> [Bool] {
    let best = largest(numbers)          // find it once
    var flags: [Bool] = []
    for number in numbers {
        flags.append(number == best)     // then ask each number about it
    }
    return flags
}

For 3, 9, 4, 9, 1 this gives [false, true, false, true, false]. What is new is only the shape of the answer: an array with one true or false for each number.

Next, give each number three more. Would three more make it at least the largest? "At least" means >=: equal is enough.

Swift
/// For each number, whether three more would make it at least the largest.
func wouldBeLargestWithThreeMore(_ numbers: [Int]) -> [Bool] {
    let best = largest(numbers)
    var flags: [Bool] = []
    for number in numbers {
        flags.append(number + 3 >= best)
    }
    return flags
}

For 4, 2, 7 and 5 this gives [true, false, true, true]. The 4 becomes 7, which ties the largest, and a tie counts. The 2 becomes 5, which is not enough.

Then the problem itself. The three becomes extraCandies, and the numbers become candies. Written out whole, with no helper, it is the shape and then one more loop:

Swift
/// LeetCode 1431. For each child: would all the extra candies give them
/// at least as many as anyone?
func kidsWithCandies(_ candies: [Int], _ extraCandies: Int) -> [Bool] {
    var most = candies[0]
    for count in candies {
        if count > most {
            most = count
        }
    }
    var answers: [Bool] = []
    for count in candies {
        answers.append(count + extraCandies >= most)
    }
    return answers
}

For the same four children and 3 extra candies it gives [true, false, true, true]. Notice what you did not have to think about: finding the largest. It was already yours.

What goes wrong

Starting from zero. var best = 0 is right only when the array happens to hold nothing below zero. Start from numbers[0].

Starting from a made-up extreme. var best = Int.min does work for the largest, because every Int is at least Int.min. But it is one more thing to get right, and for an empty array it hands back Int.min as if it were an answer. Starting from the first element says what you mean.

An empty array. numbers[0] stops the program when there is no first number. The problems here promise at least one. When a problem does not promise it, decide what an empty array means before the loop: return early, or return nil.

The wrong side of a tie. > keeps the first of equals and >= keeps the last. It only shows when you return a position or a word, which is exactly when it matters.

Keeping the wrong thing. Asked for the longest word, keep the word. Asked where the largest is, keep the position. The chair holds whatever the problem wants back.

Say it back

1

What do you have to remember as you walk along the array?

Show the answerHide the answer

One thing: the best seen so far.

2

What does best start as, and why?

Show the answerHide the answer

The first element. After one element it really is the best so far. A made-up start, like zero, may be a value that is not in the array.

3

Which part of the loop says what "best" means?

Show the answerHide the answer

The comparison in the if. > finds the largest and < finds the smallest. Nothing else changes.

4

Two numbers tie for the largest. Which position does > keep, and which does >= keep?

Show the answerHide the answer

> keeps the first, because an equal number is not strictly bigger. >= keeps the last.

5

You are asked for the longest word. What goes in the chair, and what is compared?

Show the answerHide the answer

The word goes in the chair. Its count is what is compared.

6

How did Zero win a singing contest it never entered?

Show the answerHide the answer

Someone wrote var best = 0. Zero was in the chair before the first singer walked up, and every score that night was below zero.

Practise

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

ProblemLevel
1The largest numberEasy
2The smallest numberEasy
3Where the largest isEasy
4The longest wordEasy
5The smallest and the largest in one passEasy
6How many are the largest?Easy
7Zero wins a contest it never enteredEasy
8Is each number the largest?Easy
9Would three more make it the largest?Easy
10Kids with the greatest number of candiesEasy

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.