Runs
Keep the length of the run you are in, start again when the element changes, and remember that the last run ends where nothing changes to tell you.
- Reach for it when
- The problem says consecutive, in a row, or groups of the same.
- The move
- Keep the length of the current run. When the element changes, the run has ended: use it and start again. The last run ends at the end of the array, where nothing changes to tell you.
- Cost
- O(n) time, O(1) extra space.
The idea
My practice app says my longest streak is two days. I've practised every day this week except Tuesday.
Then it's wrong. Hold on to that. Here are six numbers: 2, 2, 7, 7, 7, 3. What's a run?
Equal numbers side by side. Two 2s, three 7s, one 3.
And the longest?
Three. The 7s.
You saw that at a glance. Walk it instead, one number at a time. What do you have to carry?
How long the run I'm in has gone on. If the next number is the same as the last one, the run grows by one.
And if it's different?
Then the run I was in is over, and a new one has started, one number long.
So you carry two things. The run you're in, and the best run so far, from "Best so far".
It's a streak. Every day you practise, the streak goes up. Miss a day, and it's back to the start.
And when do you compare the streak with your best?
When it ends, surely. That's when you know how long it was.
And when does the streak you're on right now end?
It hasn't. I'm still on it.
Then a program that only looks at a streak when it ends has never looked at yours.
That is the tool. Walk once, carrying the length of the run you are in. When the element is the same as the one before, the run grows. When it differs, a new run starts. And the run you are in when the array ends is a run too, with nothing after it to say it is over.
The shape
This is what you know by heart.
/// The length of the longest run: equal numbers side by side. `numbers` is never empty.
func longestRun(_ numbers: [Int]) -> Int {
var current = 1 // the run so far: the first number alone
var best = 1
for i in 1..<numbers.count {
if numbers[i] == numbers[i - 1] { // the same as before: the run goes on
current += 1
} else { // different: a new run starts here
current = 1
}
best = max(best, current) // every time, so the last run counts
}
return best
}It has four parts, and each is there for a reason.
- The start.
currentandbestboth start at 1. The first number is a run of one, and the array is never empty. - The comparison with the one before. The loop starts at 1, because the number at position 0 has nothing before it.
numbers[i] == numbers[i - 1]is the question "Look at the neighbours" taught: is this the same as the one before? - Grow or start again. The same: the run grows by one. Different: a new run starts here, and it is one number long, so
currentgoes back to 1, not 0. - Best so far, every time.
best = max(best, current)runs on every pass, not only when a run ends. That is what makes the last run count: it is compared while it grows.
Watch it run
The numbers are [2, 2, 7, 7, 7, 3]. Here is the loop after each position.
| position | number | same as the one before? | current | best |
|---|---|---|---|---|
| 0 | 2 | (the first) | 1 | 1 |
| 1 | 2 | yes | 2 | 2 |
| 2 | 7 | no | 1 | 2 |
| 3 | 7 | yes | 2 | 2 |
| 4 | 7 | yes | 3 | 3 |
| 5 | 3 | no | 1 | 3 |
The answer is 3. Look at the third row: the 7 is different, so current goes back to 1, and best keeps the 2. Then look at the fifth row: best becomes 3 there, in the middle of the run, before the run has ended. If the 7s had come last, that line would still have caught them.
Step by step
The length of the run at the start of an array
How many numbers in a row are equal to the first one?
/// The length of the run at the start of `numbers`, which is never empty.
func firstRunLength(_ numbers: [Int]) -> Int {
var length = 1 // the first number is a run of one
for i in 1..<numbers.count {
if numbers[i] != numbers[i - 1] { // the first change: the run is over
break
}
length += 1
}
return length
}What is new: where a run ends. It ends at the first number that is different from the one before it. Then break leaves the loop, because nothing after it belongs to this run.
For 3, 3, 3, 1, 3 the answer is 3. The last 3 is equal to the first, but it is not in the first run: the 1 came between.
The longest run of 1s
The numbers are only 0s and 1s, and the question is the longest run of 1s. This is LeetCode 485.
/// LeetCode 485. The length of the longest run of 1s. `nums` holds 0s and 1s.
func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {
var current = 0 // the 1s in a row so far
var best = 0
for number in nums {
if number == 1 {
current += 1
} else {
current = 0 // a 0 ends the run
}
best = max(best, current)
}
return best
}What is new: a count that starts again. current counts the 1s in a row, and every 0 puts it back to 0. best is "Best so far", watching current.
Here a run is "1s", not "equal numbers", so each number asks about itself, not about the one before. A 0 is not in any run, so after a 0 the count is 0, not 1. And best starts at 0, which is a real answer here: an array with no 1s has no run of 1s.
For 1, 1, 0, 1, 1, 1 the answer is 3. The longest run is the last one, and it is counted, because best is updated on every pass.
The longest run of any one character
Now the run is any character repeated, and the input is a string. This is LeetCode 1446.
/// LeetCode 1446. The length of the longest run of one character. `s` is never empty.
func maxPower(_ s: String) -> Int {
let chars = Array(s)
var current = 1
var best = 1
for i in 1..<chars.count {
if chars[i] == chars[i - 1] {
current += 1
} else {
current = 1
}
best = max(best, current)
}
return best
}What is new: "the same as the one before" in place of "is it a 1". This is the shape exactly, on Array(s) from "A string as an array of characters". For "abbcccddb" the answer is 3: the three c's.
How many runs are there?
/// How many runs `numbers` holds.
func numberOfRuns(_ numbers: [Int]) -> Int {
if numbers.isEmpty {
return 0
}
var runs = 1 // the first number starts the first run
for i in 1..<numbers.count {
if numbers[i] != numbers[i - 1] { // every change starts one more
runs += 1
}
}
return runs
}What is new: counting the starts. A run starts at position 0, and a new one starts at every number that differs from the one before it. So the number of runs is 1, plus one for every change. For 4, 4, 9, 9, 9, 4 there are 3: the last 4 starts a run of its own, because it is not next to the first two.
An empty array has no runs at all, so it is answered before the loop. It is also the array for which 1..<numbers.count cannot be made: 1..<0 stops the program.
Each run as a character and a length
Now every run is wanted, not only the longest: its character and how long it is. Here each run comes back as one string, such as "a3".
/// Each run of `s` as its character and its length: "aaab" gives ["a3", "b1"].
func runsOf(_ s: String) -> [String] {
let chars = Array(s)
var runs: [String] = []
if chars.isEmpty {
return runs
}
var length = 1
for i in 1..<chars.count {
if chars[i] == chars[i - 1] {
length += 1
} else {
runs.append("\(chars[i - 1])\(length)") // the run before this is over
length = 1
}
}
runs.append("\(chars[chars.count - 1])\(length)") // the last run ends at the end
return runs
}What is new: using a run when it is over. Inside the loop, a run is over when the next character differs, so that is where it is written down: the character before, and its length. And then the last run. Nothing comes after it to differ, so the loop never writes it. The line after the loop writes it.
For "aaabcc" the answer is ["a3", "b1", "c2"]. The "c2" comes from the line after the loop. Take that line out, and the c's are never seen.
Find the bug: the last run is never counted
Here is Harper's practice app. true is a day practised.
/// The longest streak of days practised in a row. `true` is a day practised.
func longestStreak(_ days: [Bool]) -> Int {
var current = 0
var best = 0
for practised in days {
if practised {
current += 1
} else {
best = max(best, current) // the streak has ended: use it
current = 0
}
}
return best // the streak still going is never used
}It compares a streak with the best only when the streak ends, on a day missed. For a week of two days practised, one missed, then three practised, it says 2. The three days at the end are still going, so they never end, so they are never used. For three days practised and none missed it says 0.
What is new: seeing the bug and mending it with one line. The last streak ends at the end of the days. So the answer is the best of best and the streak still going:
func longestStreakFixed(_ days: [Bool]) -> Int {
var current = 0
var best = 0
for practised in days {
if practised {
current += 1
} else {
best = max(best, current)
current = 0
}
}
return max(best, current) // the last streak ends with the days
}Now the week gives 3. There are two ways to be safe from this bug, and you have seen both. Update the best on every pass, as the shape does. Or, when you only act at the end of a run, act once more after the loop.
The same by jumping: an inner loop finds where each run ends
Here is step 5 written another way. Stand at the start of a run, and walk to its end. Then jump there: that is the start of the next run.
/// Each run of `s` as its character and its length, found by jumping from run to run.
func runsByJumping(_ s: String) -> [String] {
let chars = Array(s)
var runs: [String] = []
var start = 0 // where this run starts
while start < chars.count {
var end = start
while end < chars.count && chars[end] == chars[start] {
end += 1 // on to the first that differs
}
runs.append("\(chars[start])\(end - start)") // this run is chars[start..<end]
start = end // jump to the next run
}
return runs
}What is new: two loops working together. The outer loop stands at start, the first character of a run. The inner loop moves end forward while the character is the same as at start. When it stops, the run is chars[start..<end], and its length is end - start. Then start = end jumps straight to the next run.
For "aaabcc" it gives ["a3", "b1", "c2"], the same as step 5. The lesson's code checked the two ways against each other on every string of up to eight letters made of a, b and c, 9841 strings, and they agree on all of them.
This way has no line after the loop. When the inner loop reaches the end of the string, the last run is in hand like any other, with its start and its end. That is the reason to choose it: when you need both ends of each run, jumping hands them to you.
It looks like a loop inside a loop, and a loop inside a loop is usually slow. Not here. The inner loop never goes back: each run is walked once, and then start jumps past it. So the inner loop steps over each character once. For "aaabccddddd", 11 characters, it steps 11 times. The last lesson of this unit, "How the work grows", says more about telling these two kinds of nested loop apart.
What goes wrong
The last run is never counted. A program that only acts when a run ends never acts on the last run: nothing changes after it. The streak app said 2 for a week whose last three days were practised. Update the best on every pass, or act once more after the loop.
Starting again at 0. In "the same as the one before", a new run starts with the number that differs, so it is already one long. Start it at 0 and every run after the first is counted one short: for 5, 8, 8, 8 the answer comes out 2, not 3. (In step 2's "run of 1s" a 0 is in no run, and 0 is right there.)
Comparing position 0 with the one before. There is no number before position 0. The loop starts at 1.
An empty array. 1..<numbers.count cannot be made when the array is empty, and the program stops. Answer the empty array before the loop, or say that it never comes.
Jumping without jumping. If start = end is left out, the outer loop stands at the same run for ever. And in end < chars.count && chars[end] == chars[start], the first half must come first, so that the character past the end is never read.
Say it back
What do you carry through the loop?
Show the answerHide the answer
The length of the run you are in, and the best run so far.
When the number differs from the one before, what does current become, and why?
Show the answerHide the answer
- A new run has started, and the number that differs is the first number in it.
Why does the shape update best on every pass, and not only when a run ends?
Show the answerHide the answer
So that the last run is counted. It ends at the end of the array, where nothing differs to say it is over.
When you write each run down as it ends, what else must you do?
Show the answerHide the answer
Write the last run down after the loop.
In the jumping way, why is the loop inside a loop not slow?
Show the answerHide the answer
The inner loop never goes back. Each run is walked once, then start jumps past it, so each character is stepped over once.
Why does Harper's practice app say her longest streak is two days?
Show the answerHide the answer
It only looks at a streak when the streak ends, on a day she missed. Her three days since Tuesday haven't ended. She is still on them. The last run ends where nothing changes to tell you.
Practise
These are this lesson's problems in the Orithms app, in the order they come.
| Problem | Level | |
|---|---|---|
| 1 | The run at the start | Easy |
| 2 | The longest run of 1s | Easy |
| 3 | The longest run of one character | Easy |
| 4 | Every run but the first is one short | Easy |
| 5 | How many runs? | Easy |
| 6 | Each run as a letter and a length | Easy |
| 7 | The streak still going | Easy |
| 8 | Runs by jumping | Easy |
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.