Take it as soon as you can
Go left to right, take whatever the rule allows the moment it allows it, and mark it taken so that the next decision can see it.
- Reach for it when
- You're placing or picking as many as possible, and taking one early never spoils a later one.
- The move
- Go left to right. Whenever the rule allows it, take it and mark it taken.
- Cost
- O(n) time.
- Builds on
- Look at the neighbours (2.4)
The idea
I was an usher last night, at a concert for introverts. I seated a whole row in one go, and nobody complained.
How many sat down?
All of them. We'll come back to it. The rule of the row: nobody sits right next to anybody. Seven seats, and one is already taken. How do you seat the most people?
Walk along the row from the left. At each seat, ask the two questions from last time: is the seat on the left free, and is the seat on the right free? If both are, and this seat is free, someone sits here.
Straight away? You don't look further along first, in case a better seat turns up?
There's no better seat. Taking this one only rules out the seat after it. If I waited, the person would sit further along and rule out a seat further along. That can't leave more room. It can only leave less.
So you take it the moment the rule allows. Then what?
Then I write it on the seating chart. The chart is how the next decision knows this seat is taken.
And if you don't write it down?
Then the next seat asks the chart whether its left neighbour is free, and the chart says yes. It says yes to every seat.
That's a full row.
Of people sitting side by side, all of them breaking the rule.
Is it always safe to take the first thing you can?
No. It's safe when taking something early never spoils a later choice. Here it never does. We'll meet a case where it does, and it will look exactly like this one.
So the whole trick is: be greedy, and keep the chart.
Be greedy when it's safe. And keep the chart.
That is the tool. You walk once, from left to right. Whenever the rule allows a choice, you make it at once. Then you mark it, because the rule for the next position depends on what you have already done.
The shape
This is what you know by heart. It is the last lesson's loop, "Look at the neighbours", with two lines added.
/// How many more people can sit in a row, with a free seat between any two people.
/// 0 is a free seat and 1 a taken one. No two taken seats are side by side.
func mostSeated(_ seats: [Int]) -> Int {
var seats = seats // a copy, to mark as we go
let last = seats.count - 1
var seated = 0
for i in seats.indices {
let leftIsFree = i == 0 || seats[i - 1] == 0 // nobody there, or free
let rightIsFree = i == last || seats[i + 1] == 0 // nobody there, or free
if seats[i] == 0 && leftIsFree && rightIsFree {
seats[i] = 1 // take it, and mark it taken
seated += 1
}
}
return seated
}It has four parts, and each is there for a reason.
- The copy.
var seats = seatsmakes a seating chart you are allowed to write on. A parameter is a constant in Swift, so the function cannot write on the row it was given. - The walk and the two questions. These are the last lesson's shape, unchanged. Each side passes when there is nobody there or the seat there is free.
- Take it and mark it. When the seat is free and both sides pass, someone sits down.
seats[i] = 1writes it on the chart at once, so the very next seat sees it. - The count.
seatedgoes up by one for each person seated, and it is the answer.
Watch it run
The row is [0, 0, 0, 0, 1, 0, 0]: 0 is a free seat, 1 a taken one. Here is each seat as the loop meets it, with what each side holds at that moment, and the chart afterwards.
| seat | left | right | take it? | the chart after | seated |
|---|---|---|---|---|---|
| 0 | nobody | free | yes | 1 0 0 0 1 0 0 | 1 |
| 1 | taken | free | no | 1 0 0 0 1 0 0 | 1 |
| 2 | free | free | yes | 1 0 1 0 1 0 0 | 2 |
| 3 | taken | taken | no | 1 0 1 0 1 0 0 | 2 |
| 4 | free | free | already taken | 1 0 1 0 1 0 0 | 2 |
| 5 | taken | free | no | 1 0 1 0 1 0 0 | 2 |
| 6 | free | nobody | yes | 1 0 1 0 1 0 1 | 3 |
The answer is 3. Look at the second row. Seat 1 says no because its left side is taken, and its left side is taken only because seat 0 was marked one step earlier. On the row the function was given, seat 0 is free. The chart is what makes seat 1 say no.
Step by step
Seat as many people as possible in an empty row, with a free seat between each
The row starts empty, so the function makes the row itself, all free, with Array(repeating: 0, count: count). Then it walks, and hands back the seats people take.
/// The seats people take in an empty row of `count` seats, with a free seat between
/// any two, each seat taken as soon as the rule allows.
func seatsInEmptyRow(_ count: Int) -> [Int] {
var seats = Array(repeating: 0, count: count) // the row, all free
let last = count - 1
var taken: [Int] = []
for i in seats.indices {
let leftIsFree = i == 0 || seats[i - 1] == 0
let rightIsFree = i == last || seats[i + 1] == 0
if seats[i] == 0 && leftIsFree && rightIsFree {
seats[i] = 1 // the seat is marked taken
taken.append(i)
}
}
return taken
}What is new: marking. seats[i] = 1 changes the row as the loop goes. The next seat's question about its left side reads the changed row.
For five seats the answer is [0, 2, 4], and for four it is [0, 2]. Each person rules out the seat after them, so people sit in every second seat, from the first.
Here is the same loop with the marking left out. The row is a let now, because nothing writes to it.
func seatsInEmptyRowUnmarked(_ count: Int) -> [Int] {
let seats = Array(repeating: 0, count: count) // never changed
let last = count - 1
var taken: [Int] = []
for i in seats.indices {
let leftIsFree = i == 0 || seats[i - 1] == 0
let rightIsFree = i == last || seats[i + 1] == 0
if seats[i] == 0 && leftIsFree && rightIsFree {
taken.append(i) // seated, but never marked
}
}
return taken
}For five seats it hands back [0, 1, 2, 3, 4]. Every seat of an empty row has free neighbours in the row as it started, and that row is the only one this loop ever looks at. So everybody sits down, side by side.
The same when some seats are already taken
Now the row comes in as a parameter, and some of its seats are taken already. This step is the shape itself.
What is new: the copy. The function wants to mark seats, and the row it was given is a constant. Without var seats = seats, the line that marks a seat does not compile. Swift says:
error: cannot assign through subscript: 'seats' is a 'let' constant
The copy has the same name. Inside the function, seats now means the copy, which can be written on. The caller's row is never touched.
The rest is the last lesson's loop. The seats that were taken already are 1 from the start, so the questions see them as they see a person seated a moment ago. For [0, 0, 0, 0, 1, 0, 0] the answer is 3.
Show by a trace that taking the first free seat is never worse than waiting
This step asks for a trace: how many people have sat down after each seat is looked at.
/// How many people have sat down after each seat is looked at.
func seatedAfterEachSeat(_ seats: [Int]) -> [Int] {
var seats = seats
let last = seats.count - 1
var seated = 0
var counts: [Int] = []
for i in seats.indices {
let leftIsFree = i == 0 || seats[i - 1] == 0
let rightIsFree = i == last || seats[i + 1] == 0
if seats[i] == 0 && leftIsFree && rightIsFree {
seats[i] = 1
seated += 1
}
counts.append(seated) // what `seated` holds now
}
return counts
}For the lesson's row it gives [1, 1, 2, 2, 2, 2, 3]. What is new is only the shape of the answer: one number for every seat, the value seated holds after that seat.
The point of the trace is to see the greedy choice at work, against a rule that sounds careful. Here is that rule: pass over the first seat you could take, in case waiting turns out better, and after that take seats as before.
/// The tempting other rule: pass over the first seat that could be taken, in case
/// waiting does better, and after that take each seat as soon as the rule allows.
func mostSeatedAfterWaiting(_ seats: [Int]) -> Int {
var seats = seats
let last = seats.count - 1
var seated = 0
var waited = false
for i in seats.indices {
let leftIsFree = i == 0 || seats[i - 1] == 0
let rightIsFree = i == last || seats[i + 1] == 0
if seats[i] == 0 && leftIsFree && rightIsFree {
if !waited {
waited = true // leave this one, and wait
continue
}
seats[i] = 1
seated += 1
}
}
return seated
}On three empty seats, waiting seats 1, where taking the first free seat seats 2. On five empty seats it is 2 against 3.
Here is why waiting never wins. Take the first seat a person could have. Sitting there rules out one more seat: the seat after it. Any other place for that first person is further along, and rules out a seat further along. Everything before the first possible seat was unusable anyway. So taking the first possible seat leaves at least as much room for everyone after.
The lesson's code also checks this the slow way. It tries every row of up to ten seats where no two taken seats are side by side, 375 rows, and for each one it tries every possible choice of seats. Taking the first free seat always seats as many people as the best choice there is. Waiting is never better, and on some rows it is worse.
Stop as soon as enough people are seated
Often the question is not "how many?" but "is there room for this many?". Then the loop can stop the moment the answer is known.
/// Whether `people` more people can sit in the row, with a free seat between any two.
func canSeat(_ seats: [Int], _ people: Int) -> Bool {
var seats = seats
let last = seats.count - 1
var seated = 0
for i in seats.indices {
let leftIsFree = i == 0 || seats[i - 1] == 0
let rightIsFree = i == last || seats[i + 1] == 0
if seats[i] == 0 && leftIsFree && rightIsFree {
seats[i] = 1
seated += 1
if seated == people { // enough: it cannot change now
return true
}
}
}
return seated >= people // right too when people is 0
}What is new: an early return true inside the loop. Once seated reaches people, nothing later can take it back down, so the answer is settled. This is the "is there any?" move from "Count as you go", where a yes can be given at the first sign.
For the lesson's row, true for three people and false for four. On a row of 20,000 free seats with two people to seat, it looks at 3 seats and answers.
Look at the last line too. When people is 0, nobody needs a seat, and the answer is yes even for a full row. The early return never fires for 0, because seated is at least 1 by the time it is compared. So the last line, seated >= people, gives the yes.
Buy as many items as a budget allows, cheapest first
The same tool on something that is not a row. You have a budget, and a list of prices, one of each item. How many items can you buy?
/// The most items `budget` can buy, one of each, buying the cheapest first.
func mostItems(_ prices: [Int], _ budget: Int) -> Int {
var left = budget
var bought = 0
for price in prices.sorted() { // cheapest first
if price > left { // too dear, and so is every one after
break
}
left -= price
bought += 1
}
return bought
}What is new: putting things in an order first, so that "take it as soon as you can" means the right thing. Sorted cheapest first, the first item you can afford is the one to buy. sorted() is from "Sorting by a key".
For the prices 5, 1, 3 and 2 and a budget of 6, the answer is 3: 1, 2 and 3. The break is safe because the prices are sorted. If this price is too dear, every price after it is at least as dear.
Why cheapest first is safe: suppose some set of items fits the budget. Swap each one for a cheaper item you did not take, and the total only goes down, so it still fits. So the cheapest items always fit when any items that many fit.
Now the warning Arthur gave. Change the question to "spend as much of the budget as you can", and try the same tool with the dearest item first. For 6, 5 and 5 and a budget of 10, it takes the 6, and then neither 5 fits. It spends 6. Buying the two 5s spends 10.
/// The most of `budget` that can be spent, taking the dearest item that still fits first.
/// It looks like the same tool. It is not safe here.
func spentDearestFirst(_ prices: [Int], _ budget: Int) -> Int {
var left = budget
for price in prices.sorted(by: >) { // dearest first
if price <= left {
left -= price
}
}
return budget - left
}It looks like the same tool. It is not safe here, because taking the 6 early spoils a later choice: it uses up the room two items needed. That is the test to make before you are greedy: does taking this now ever spoil something later? For seats and for the cheapest items, no. For spending the most, yes. A later lesson has the tool for that kind of problem.
Can Place Flowers
A flowerbed is a row of plots. Some have a flower in them already, and no two flowers are ever in neighbouring plots. You are asked whether n more flowers can be planted with that still true.
It is step 4 again with new words: plots for seats, flowers for people. It comes in three small steps.
First, plant everywhere you can, and show the bed. Walk the bed and plant in every plot whose plot is empty and whose two sides pass. Hand back the bed itself, so you can see the marking.
/// The flowerbed after a flower is planted in every plot that allows one, left to right.
/// 0 is an empty plot and 1 a planted one.
func plantEverywhere(_ flowerbed: [Int]) -> [Int] {
var bed = flowerbed
let last = bed.count - 1
for i in bed.indices {
let leftIsEmpty = i == 0 || bed[i - 1] == 0
let rightIsEmpty = i == last || bed[i + 1] == 0
if bed[i] == 0 && leftIsEmpty && rightIsEmpty {
bed[i] = 1
}
}
return bed
}For the bed 1, 0, 0, 0, 0, 0 it gives [1, 0, 1, 0, 1, 0]. The flower at the far end goes in because past the edge counts as empty, as in "Look at the neighbours".
Next, stop as soon as n flowers are in, and say how many went in.
/// How many flowers go in before the planting stops. It stops as soon as `n` are in.
func plantedUpTo(_ flowerbed: [Int], _ n: Int) -> Int {
if n == 0 { // nothing to plant: stop before looking
return 0
}
var bed = flowerbed
let last = bed.count - 1
var planted = 0
for i in bed.indices {
let leftIsEmpty = i == 0 || bed[i - 1] == 0
let rightIsEmpty = i == last || bed[i + 1] == 0
if bed[i] == 0 && leftIsEmpty && rightIsEmpty {
bed[i] = 1
planted += 1
if planted == n {
return planted
}
}
}
return planted
}On five empty plots, with 2 to plant it stops at 2, and with 5 to plant it can only manage 3. Notice the first line. If n is 0, the loop would plant one flower before it ever compared, so the function stops before looking.
Then the problem itself. LeetCode wants a yes or a no, so the count becomes step 4's two returns:
/// LeetCode 605. Whether `n` new flowers fit in the bed, with no two side by side.
func canPlaceFlowers(_ flowerbed: [Int], _ n: Int) -> Bool {
var bed = flowerbed
let last = bed.count - 1
var planted = 0
for i in bed.indices {
let leftIsEmpty = i == 0 || bed[i - 1] == 0
let rightIsEmpty = i == last || bed[i + 1] == 0
if bed[i] == 0 && leftIsEmpty && rightIsEmpty {
bed[i] = 1
planted += 1
if planted == n {
return true
}
}
}
return planted >= n
}For 0, 0, 1, 0, 0 it says true for two flowers and false for three. There is nothing in it you have not already written: the walk, the two questions, the mark, the count, and the early yes.
What goes wrong
Not marking. Without seats[i] = 1, every decision is made against the row as it started, and on an empty row of five, everybody sits down: [0, 1, 2, 3, 4]. Whenever one choice changes what the next one is allowed to do, write the choice down before you move on.
Marking the row you were given. It does not compile. A parameter is a constant: make a copy with var seats = seats and mark that.
The ends. The two end seats each have one neighbour. Past the edge counts as free, as in the last lesson. Ask whether there is a neighbour before you read one, and || keeps you inside the row.
Asked for zero. "Can 0 people sit down?" is yes, even in a full row. A loop that plants first and compares after gets this wrong: say so before the loop, or end with >=, as step 4 does.
Being greedy where it is not safe. Taking the dearest item first, to spend the most, spends 6 of 10 where 10 was possible. Before you take the first thing you can, ask whether taking it ever spoils a later choice.
Say it back
When is "take it as soon as you can" safe?
Show the answerHide the answer
When taking something early never spoils a later choice. For a row of seats, the first possible seat rules out only the seat after it, and waiting can only rule out a seat further along.
What does seats[i] = 1 do in the shape, and what goes wrong without it?
Show the answerHide the answer
It writes the choice on the chart, so the next seat's questions see it. Without it every decision is made against the starting row, and people sit side by side.
Why does the shape start with var seats = seats?
Show the answerHide the answer
The row comes in as a parameter, and a parameter is a constant. Marking it does not compile, so the function makes a copy to mark.
In canSeat, why is the last line seated >= people and not false?
Show the answerHide the answer
Because the early return only fires when someone has just been seated. When people is 0, nobody needs a seat, the early return never fires, and the answer is still yes.
Why is break safe in mostItems?
Show the answerHide the answer
The prices are sorted cheapest first. If one is too dear for what is left, every price after it is at least as dear.
How did Harper seat a whole row of introverts, side by side, without one complaint?
Show the answerHide the answer
She never wrote anyone on the seating chart. Each seat asked the chart whether its neighbours were free, and the chart still showed the empty row it started as, so every seat said yes. Nobody complained because they were introverts. Keep the chart.
Practise
These are this lesson's problems in the Orithms app, in the order they come.
| Problem | Level | |
|---|---|---|
| 1 | Every second seat | Easy |
| 2 | Everybody sits down | Easy |
| 3 | Seat the most | Easy |
| 4 | The trace of a greedy row | Easy |
| 5 | Room for them all? | Easy |
| 6 | Nobody needs a seat | Easy |
| 7 | The most items on a budget | Easy |
| 8 | Plant everywhere you can | Easy |
| 9 | Stop as soon as n are in | Easy |
| 10 | Can place flowers | 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.