Two best so far
Two variables, each with a meaning you can say in one sentence, kept true for every number the loop meets.
- Reach for it when
- The problem wants the second largest, or a pair or triple that goes upwards.
- The move
- Two variables, each with an exact meaning. Every element updates at most one of them.
- Cost
- O(n) time, O(1) extra space.
- Builds on
- Best so far (2.1)
The idea
I judged a race with two medals, gold and silver. One runner went home with both.
Was she twice as fast?
She was the fastest. We'll come back to the silver. You remember the chair from "Best so far"?
One chair, the best so far sits in it, and each number gets one chance to take it.
Now the question wants the two largest. Gold and silver.
Then it's a podium with two steps. Gold on the top step, silver on the lower.
A new number arrives. What can happen?
Three things. It beats gold: it takes the top step, and the old gold steps down to silver. It beats only silver: it takes silver, and gold doesn't move. Or it beats neither, and walks on.
When the new winner takes gold, who moves first?
The old gold steps down first. If the winner steps up first, there's no old gold left to step down. You'd be handing silver to a copy of the new winner.
Which is how one runner got both medals.
That, and somebody wrote the two lines in the wrong order.
At the end of this lesson the two variables stop meaning gold and silver. They mean something stranger.
As long as I can say what each one means in a sentence, I'll follow them anywhere.
That's the whole tool, isn't it?
It is. Two variables, two sentences, and every number keeps both sentences true.
That is the tool. You carry two values, and each has an exact meaning you could say out loud. Each number that arrives is shown to them in order, and the loop keeps both meanings true after every number.
The shape
This is what you know by heart: the two largest numbers.
/// The largest and the second largest of `numbers`, in that order. The second equals the
/// first when the largest is there twice. `numbers` holds at least two numbers.
func twoLargest(_ numbers: [Int]) -> [Int] {
var gold = max(numbers[0], numbers[1]) // start from the first two, in order
var silver = min(numbers[0], numbers[1])
for i in 2..<numbers.count {
let number = numbers[i]
if number > gold {
silver = gold // the old gold steps down first
gold = number
} else if number > silver {
silver = number // between the two: silver only
}
}
return [gold, silver]
}It has four parts, and each is there for a reason.
- The start. The first two numbers, put in order: the larger is gold and the smaller is silver. That is starting from something real, as "Best so far" taught. The array holds at least two numbers, so both exist.
- A new gold. When a number beats gold, two things change, in this order:
silver = gold, thengold = number. The old gold steps down before the new one steps up. - A new silver. When a number beats only silver, silver changes and gold does not.
else ifmakes sure a new gold is not also tested against silver. - The two meanings. After every number,
goldis the largest number met so far, andsilverthe second largest. When the largest is there twice, silver is the same number as gold: both are real numbers from the array.
Watch it run
The numbers are [3, 9, 4, 9, 1]. The table starts after the first two.
| number | goes to | gold | silver |
|---|---|---|---|
| 3, 9 | the start | 9 | 3 |
| 4 | silver | 9 | 4 |
| 9 | silver | 9 | 9 |
| 1 | nowhere | 9 | 9 |
The answer is [9, 9]. Look at the third row. The second 9 is not bigger than gold, which is 9 too, so it cannot take gold. It is bigger than silver, so it takes silver. Two 9s, two places.
Step by step
The two largest numbers
This step is the shape itself, written from an empty function.
What is new: a second chair, and the order in which the chairs change. Here are the two lines the wrong way round:
func twoLargestWrongOrder(_ numbers: [Int]) -> [Int] {
var gold = max(numbers[0], numbers[1])
var silver = min(numbers[0], numbers[1])
for i in 2..<numbers.count {
let number = numbers[i]
if number > gold {
gold = number // gold first...
silver = gold // ...so silver gets the new gold
} else if number > silver {
silver = number
}
}
return [gold, silver]
}For 3, 4, 9 it gives [9, 9]. When 9 arrives, gold = number makes gold 9, and then silver = gold copies that same 9 into silver. The 4 that was gold is lost. The right order gives [9, 4].
Say the rule as you write it: the old one moves down before the new one moves in.
The second largest different number
Now the second number must be different from the largest. For [3, 9, 4, 9, 1] that is 4, not 9.
/// The second largest number that is different from the largest, or nil when every
/// number is the same. `numbers` is never empty.
func secondLargestDifferent(_ numbers: [Int]) -> Int? {
var gold = numbers[0]
var silver: Int? = nil // there may be no second at all
for number in numbers {
if number > gold {
silver = gold
gold = number
} else if number < gold && number > (silver ?? Int.min) {
silver = number // equal to gold is not a second
}
}
return silver
}What is new: a number equal to gold is turned away. It may not take silver, because silver must be different. So the test for silver is "smaller than gold and bigger than silver".
There may also be no second at all. When every number is the same, nothing is different from the largest. So silver is an optional that starts as nil, and the function hands back nil when it is still empty. silver ?? Int.min reads nil as lower than any number, so the first number that is different from gold always takes silver.
Gold starts as the first number and the loop meets it again. That does no harm: it is not bigger than gold, and it is not smaller.
The two smallest
/// The smallest and the second smallest of `numbers`, in that order.
/// `numbers` holds at least two numbers.
func twoSmallest(_ numbers: [Int]) -> [Int] {
var low = min(numbers[0], numbers[1])
var nextLow = max(numbers[0], numbers[1])
for i in 2..<numbers.count {
let number = numbers[i]
if number < low {
nextLow = low
low = number
} else if number < nextLow {
nextLow = number
}
}
return [low, nextLow]
}What is new: only the comparisons. > becomes <, and the names say what the chairs hold now. For [3, 9, 4, 9, 1] the answer is [1, 3]. The order of the two lines is the same rule: the old smallest moves to second before the new smallest moves in.
Is there a number that comes after a smaller one?
The question changes shape here. It is not about the two largest any more. It asks whether some number has a smaller number anywhere before it.
/// Whether some number comes after a smaller one, anywhere before it.
/// `numbers` is never empty.
func hasRisingPair(_ numbers: [Int]) -> Bool {
var smallest = numbers[0]
for number in numbers {
if number > smallest { // something smaller came before it
return true
}
smallest = number // not bigger, so it is the new smallest
}
return false
}What is new: carrying the smallest so far in order to judge the numbers after it. If a number is bigger than the smallest so far, then something smaller came before it, and the answer is yes. If it is not bigger, then it is the smallest so far itself, and it takes the chair.
For 5, 3, 4 the answer is true: 4 comes after 3. For 5, 3, 3, 1 it is false. Every number there is the smallest so far when it arrives, and an equal number is not bigger.
Keep first, the smallest so far, and second, the smallest number that had something smaller before it
Here are the two variables of LeetCode 334, and their two sentences.
firstis the smallest number met so far.secondis the smallest number met so far that had something smaller before it.
A number that had something smaller before it is the top of a rising pair. So second is the lowest top of any rising pair met so far.
/// `first` and `second` after every number: `[first]` while there is no second yet.
/// Every number is between -1,000,000 and 1,000,000.
func firstAndSecond(_ numbers: [Int]) -> [Int] {
var first = Int.max // the smallest so far
var second = Int.max // smallest with a smaller one before it
for number in numbers {
if number <= first {
first = number
} else if number <= second {
second = number
}
}
return second == Int.max ? [first] : [first, second]
}What is new: two variables whose meanings are not gold and silver. Each number goes to one place at most. If it is no bigger than first, it is the new smallest. If it is bigger than first, then first came before it and is smaller, so it is the top of a rising pair, and it takes second when it is lower than the second already there.
Both start at Int.max. That would be wrong in "Best so far", where a made-up start could be handed back as the answer. It is right here for two reasons. first never keeps it: the very first number is no bigger than Int.max, so it takes first at once. And second can keep it only while no rising pair has been met, which is exactly what Int.max stands for: no pair yet, so any real top beats it. The function says so at the end, by handing back only first when second was never set. The numbers here are kept between -1,000,000 and 1,000,000, so Int.max can never be one of them.
For 5, 6, 1, 2 the answer is [1, 2]: 1 is the smallest, and 2 is the lowest top, since 1 came before it.
Show by a trace why replacing first never breaks second
Here is the step learners do not believe at first. Watch first and second on 5, 6, 1, 7.
| number | what it does | first | second |
|---|---|---|---|
| 5 | the new first | 5 | none |
| 6 | the new second | 5 | 6 |
| 1 | the new first | 1 | 6 |
| 7 | bigger than second: a triple | 1 | 6 |
Look at the third row. first becomes 1, and the 1 comes after the 6 that second holds. It looks as if the two variables no longer make a pair: 1 is not before 6.
They were never meant to make a pair. Read the two sentences again. second is 6 because 6 had something smaller before it: the 5. That is still true after the 1 arrives. Nothing that happens later can change what came before the 6. So when 7 arrives and is bigger than second, there really is a triple: 5, 6, 7.
And first is now 1 for the numbers still to come. If a 2 arrived next, it would be bigger than first, so it would be the top of the pair 1, 2, and it would take second, because 2 is lower than 6. A lower second is easier to beat. Both sentences stay true after every number, and that is all the loop needs.
Here is the same trace as a function. After every number it writes down the two variables, [first] alone while there is no second yet:
/// `first` and `second` after each number, as `firstAndSecond` would give them there.
func firstAndSecondAfterEach(_ numbers: [Int]) -> [[Int]] {
var first = Int.max
var second = Int.max
var trace: [[Int]] = []
for number in numbers {
if number <= first {
first = number
} else if number <= second {
second = number
}
trace.append(second == Int.max ? [first] : [first, second])
}
return trace
}For 5, 6, 1, 7 it gives [[5], [5, 6], [1, 6], [1, 6]]. What is new in this step is only the shape of the answer: the state of the loop after every number, so that you can check it against the two sentences row by row.
Increasing Triplet Subsequence
You are given an array of numbers. Is there a number, then a bigger number somewhere after it, then a bigger one again somewhere after that? The three need not be side by side, and equal does not count as bigger.
It comes in two small steps, and then the whole.
First, every number that rises above an earlier one. Collect each number that has a smaller number somewhere before it. This is step 4's question asked of every number, with the smallest so far kept as before.
/// Every number that has a smaller number somewhere before it, in order.
func risers(_ nums: [Int]) -> [Int] {
var smallest = Int.max
var found: [Int] = []
for number in nums {
if number > smallest {
found.append(number)
} else {
smallest = number
}
}
return found
}For 5, 6, 1, 2, 7 it gives [6, 2, 7]. Every one of these could be the middle of a triple, and the lowest of them, the 2, is the one second keeps, because it is the easiest to beat.
Next, the first number bigger than second. With first and second kept as in step 5, a number bigger than second is the third of a triple: second had something smaller before it, and this number is bigger than second and comes after it. Hand back where the first such number is.
/// The position of the first number that is bigger than `second`: the third of an
/// increasing triple. nil when there is none.
func thirdPosition(_ nums: [Int]) -> Int? {
var first = Int.max
var second = Int.max
for i in nums.indices {
let number = nums[i]
if number <= first {
first = number
} else if number <= second {
second = number
} else {
return i // bigger than second: the third
}
}
return nil
}For 5, 6, 1, 7 it gives 3: the 7, which completes 5, 6, 7. Notice the else. A number is tested against first, then against second, and only a number bigger than both gets that far.
Then the problem itself. LeetCode only wants a yes or a no:
/// LeetCode 334. Whether three numbers, in order, go strictly upwards.
func increasingTriplet(_ nums: [Int]) -> Bool {
var first = Int.max // the smallest so far
var second = Int.max // smallest with a smaller one before it
for number in nums {
if number <= first {
first = number
} else if number <= second {
second = number
} else {
return true // bigger than second: a triple
}
}
return false
}For 5, 6, 1, 7 it says true, and for 4, 4, 4, 4 it says false: equal is not bigger, so every 4 stays at first. The lesson's code checked it against the slow way, which tries every three positions, on every array of up to seven numbers from 0 to 3, 21845 arrays. They agree on every one.
It walks the array once, with two variables. That is the whole of a problem LeetCode marks Medium.
What goes wrong
The two lines in the wrong order. gold = number before silver = gold copies the new gold into silver, and the old gold is lost: 3, 4, 9 gives [9, 9]. The old one moves down before the new one moves in.
Letting equal take the wrong place. For the two largest, a second 9 belongs in silver. For the second largest different number, it belongs nowhere. For an increasing triple, a number equal to first must stay at first, so the test is <=, not <. Decide what equal means before you choose the comparison.
Testing both chairs. Without else, a number that took gold would also be tested for silver. Each number goes to one place at most.
A start that can be handed back. Int.max is safe in LeetCode 334 because it is never the answer: it only stands for "no pair yet". In a function that returns a chair, check before you return it, as step 5 does.
Believing first and second are a pair. After first moves, it can sit after second in the array. That is fine. second keeps its own sentence, and the triple it promises is real.
Say it back
When a number beats gold, which line comes first, and why?
Show the answerHide the answer
silver = gold. The old gold steps down before the new one steps up. The other way round, silver gets a copy of the new gold.
Why is the start the first two numbers, in order, and not two zeros?
Show the answerHide the answer
Start from something real. Zero may not be in the array, and could be handed back as gold or silver.
Say what first and second mean in LeetCode 334.
Show the answerHide the answer
first is the smallest number so far. second is the smallest number so far that had something smaller before it.
first has moved to a number after second. Is the next number bigger than second still the third of a triple?
Show the answerHide the answer
Yes. second had something smaller before it when it was set, and that is still true. The triple is that smaller number, second, and the new number.
Why is Int.max a safe start in LeetCode 334, when a made-up start was wrong in "Best so far"?
Show the answerHide the answer
It is never handed back as the answer. The first number replaces first at once, and second at Int.max only means "no pair yet", which no number can beat.
How did one runner win both gold and silver?
Show the answerHide the answer
She took gold before the old gold stepped down. gold = number, then silver = gold: the medal for second place went to a copy of her. The old one moves down before the new one moves in.
Practise
These are this lesson's problems in the Orithms app, in the order they come.
| Problem | Level | |
|---|---|---|
| 1 | Gold and silver | Easy |
| 2 | One runner, both medals | Easy |
| 3 | The second largest, different | Easy |
| 4 | The two smallest | Easy |
| 5 | A number after a smaller one | Easy |
| 6 | First and second | Easy |
| 7 | The trace of first and second | Easy |
| 8 | Every number that rises | Easy |
| 9 | Where the triple is completed | Medium |
| 10 | Increasing triplet subsequence | 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.