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

Look at the neighbours

A rule about what is next door reads the position before and the position after, and at either end the neighbour who is not there is never read: it counts as whatever lets the rule pass.

Reach for it when
The rule is about what's next door: no two adjacent, bigger than both sides.
The move
Read i - 1 and i + 1. At either end, treat the missing neighbour as whatever lets the rule pass.
Cost
O(n) time, O(1) extra space.

The idea

Harper

The best neighbour I ever had didn't exist.

Arthur

Quiet, I imagine.

Harper

Never a sound. We'll come back to them. You know the street from "Loops and indexes": houses in a row, a number on every door. Tonight some of the houses have a drummer in them. A drummer next door keeps me awake, and one two doors away doesn't. I'm at number 3. Do I sleep?

Arthur

I look at number 2 and at number 4, and nowhere else. The rule is about next door, so next door is all I read. If your house is i, they are i - 1 and i + 1.

Harper

Easy. Now I move to number 0, the first house in the street. Do I sleep?

Arthur

I look at number 1. Then I look for number minus one, and the street has no such house.

Harper

Look anyway. What does Swift say is there?

Arthur

It doesn't say "nobody". Reading numbers[-1] stops the program. The last house has the same trouble on its other side: it has no i + 1.

Harper

So the two end houses are the awkward ones. One neighbour each.

Arthur

They are the whole difficulty of this lesson. The middle of the street is easy.

Harper

Then I'll write the first house a little test of its own, and the last house another.

Arthur

You can, and we will, once. Then a street of one house turns up. It is the first house and the last house at the same time, and it wants a third.

Harper

There has to be a better question.

Arthur

There is, and every house can be asked it, about each side in turn. Is there nobody there, or somebody quiet?

Harper

Nobody counts as quiet?

Arthur

Nobody is as quiet as it gets. The rule is "no drummer next door", and a house that isn't there has no drummer in it.

Harper

And you don't go round to make sure?

Arthur

That is why "nobody there" is asked first. i == 0 || numbers[i - 1] == 0. When i is 0 the first half is true, and || stops there. The second half never runs. Nobody knocks at a house that isn't there.

Harper

Which brings me back to my neighbour.

Arthur

You had the end house.

Harper

"Quiet on one side, guaranteed." It was the only true thing the estate agent said.

That is the whole tool: a rule about what is next door reads i - 1 and i + 1, and a neighbour who is not there is never read. It counts as whatever lets the rule pass. The rest of this lesson is how to reach the two ends of the street without falling off them, one small step at a time.

Here is a street of six houses, drawn twice. A 1 is a house with a drummer in it, and a 0 is a quiet house. Harper's house is the one in brackets: it is i, and her neighbours are marked under theirs.

position            0      1      2      3      4      5
number              0      0      1     [0]     0      0
                                i - 1    i    i + 1

At number 3 both neighbours are real houses, and one of them has the drummer: she does not sleep. Now she moves to number 0.

position            0      1      2      3      4      5
number    nobody   [0]     0      1      0      0      0
           i - 1    i    i + 1

Her i + 1 is house 1, which is quiet. Her i - 1 is nobody: the street has no house there to read. She sleeps.

The shape

This is what you know by heart. It answers Harper's question for every house at once. It finds the positions of each 0 whose neighbours are both 0, where past either end of the street counts as 0.

Swift
/// The positions of each 0 whose neighbours are both 0. Past either end counts as 0.
func zerosWithZeroNeighbours(_ numbers: [Int]) -> [Int] {
    let last = numbers.count - 1                              // the last position
    var positions: [Int] = []
    for i in numbers.indices {                                // every house, both ends
        let leftIsZero = i == 0 || numbers[i - 1] == 0        // nobody there, or a 0
        let rightIsZero = i == last || numbers[i + 1] == 0    // nobody there, or a 0
        if numbers[i] == 0 && leftIsZero && rightIsZero {
            positions.append(i)
        }
    }
    return positions
}

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

Inside each || the order matters: whether a neighbour is there is asked before the neighbour is read. Step 5 says why that makes it safe.

Watch it run

The street is 0, 0, 1, 0, 0 and 0. Here is every pass: what was read on each side, and what the two questions said.

inumbers[i]read on the leftleftIsZeroread on the rightrightIsZerokept?
00nobodytrue0trueyes
100true1falseno
210true0trueno
301false0trueno
400true0trueyes
500truenobodytrueyes

The answer is [0, 4, 5]. Look at the first row. Nothing was read on the left of house 0, because there is no house there to read, and leftIsZero is true all the same: i == 0 settled it. The last row is its mirror on the right. Those two rows are this tool.

Then look at the third row. Both sides of house 2 passed, and it is still not kept: it is the house with the drummer in it.

Step by step

The first four steps reach the shape the long way round, one end of the street at a time. The fifth is the shape.

Step 1

Is each number bigger than the one before it?

Start with a rule that looks one way only: back, at the house before.

Swift
/// Whether each number is bigger than the one before it. `numbers` is never empty.
func goesUp(_ numbers: [Int]) -> Bool {
    for i in 1..<numbers.count {                 // from 1: house 0 has nobody before it
        if numbers[i] <= numbers[i - 1] {        // not bigger than the one before
            return false
        }
    }
    return true
}

You have looked back like this before: in "Count as you go" you counted the numbers larger than the one before them. That lesson also had "are all" questions, which answer false at the first number that fails and true when the loop is through.

What is new: the two are joined. The loop looks back at numbers[i - 1], and a number fails when it is not bigger than the one before it. Not bigger is <=: an equal number fails too.

For 2, 5, 6 and 9 the answer is true. For 2, 5, 5 and 9 it is false: the second 5 is not bigger than the first.

Now look at the 1 in 1..<numbers.count with this lesson's eyes. House 0 has nobody before it. The loop never stands on house 0, so numbers[i - 1] is always a real house. That is the first way to deal with a neighbour who is not there: do not ask the house that lacks one. It works here because the first house has nothing to be bigger than, so it has nothing to answer.

Start the loop at 0 and house 0 is asked about a neighbour it does not have. One of this step's problems is that loop, to mend.

The problems promise at least one number. With one number the range is 1..<1, which holds nothing: the loop does not run, and the answer is true, because no number failed.

Step 2

How many numbers are bigger than both their neighbours?

A number that is bigger than both its neighbours is called a peak. Read the numbers as the heights of the houses, and a peak is a roof that stands above the roof on each side.

This step holds three new things, so it comes in three parts, and each part has a problem of its own.

First, only the houses with a neighbour on each side.

Swift
/// How many numbers have a neighbour on each side and are bigger than both of them.
/// `numbers` holds at least two numbers.
func countOfMiddlePeaks(_ numbers: [Int]) -> Int {
    var count = 0
    for i in 1..<numbers.count - 1 {             // from 1 to the one before the last
        if numbers[i] > numbers[i - 1] && numbers[i] > numbers[i + 1] {
            count += 1
        }
    }
    return count
}

What is new: the body reads numbers[i + 1], the house after, and the last house has nobody after it. So the loop stops one house early as well as starting one house late: 1..<numbers.count - 1 is every house except the two end houses. For 5, 1, 4, 2 and 9 the count is 1: the 4, which stands above the 1 and the 2. The 5 and the 9 are never asked.

Run the loop on to the last house, with 1..<numbers.count, and numbers[i + 1] asks for a house past the end of the street. One of this step's problems is that loop, to mend.

Next, a street too short for the range. These problems promise at least two numbers, and the promise is doing work. With two numbers the range is 1..<1: it holds nothing, and the count is 0. With one number it would be 1..<0, and with none 1..<-1. Swift cannot make a range that ends before it starts, and the program stops before the loop begins. When nothing promises the numbers, ask before the range is made:

Swift
if numbers.count < 3 {                       // nobody has a neighbour on each side
    return 0
}

What is new: a question before the loop, about how long the street is. With fewer than three houses, no house has a neighbour on each side. So the answer is 0, and the range is never made. Now an array of one number gives 0, and an array of none gives 0. It is the "ask first" of "A grid", asked about a range.

Then the two end houses. The step's own words are that the two ends have one neighbour each. So an end house is a peak when it is bigger than its one neighbour.

Swift
/// How many numbers are peaks: bigger than both their neighbours. A number at either
/// end has one neighbour, and has only that one to be bigger than.
/// `numbers` holds at least two numbers.
func countOfPeaks(_ numbers: [Int]) -> Int {
    let last = numbers.count - 1                 // the last position
    var count = 0
    if numbers[0] > numbers[1] {                 // the first house: one neighbour
        count += 1
    }
    for i in 1..<last {                          // the middle: two neighbours
        if numbers[i] > numbers[i - 1] && numbers[i] > numbers[i + 1] {
            count += 1
        }
    }
    if numbers[last] > numbers[last - 1] {       // the last house: one neighbour
        count += 1
    }
    return count
}

What is new: each end house gets an if of its own, about the one neighbour it has. The first house is asked before the loop, and the last house after it. For the same five numbers the count is 3: the 5 stands above the 1, the 4 is counted as before, and the 9 stands above the 2.

One rule now takes three pieces of code. It still leans on the promise of two numbers, too: on a street of one house, numbers[1] is not there. Keep that in mind until step 5.

Step 3

Is any 1 next to another 1?

From here on the numbers are only 0s and 1s, as on Harper's street: a 1 is a house with a drummer in it. The question is whether two drummers live next door to each other. Problems have a word for next door: two positions side by side are adjacent.

Swift
/// Whether any 1 is next to another 1. `numbers` holds 0s and 1s, and is never empty.
func hasAdjacentOnes(_ numbers: [Int]) -> Bool {
    for i in 1..<numbers.count {
        if numbers[i] == 1 && numbers[i - 1] == 1 {      // this house and the one before
            return true
        }
    }
    return false
}

What is new: a rule about a pair needs one look, not two. Each house looks back at the one before it, and that is enough. Every pair of neighbours is met once, when the loop stands on the second house of the pair. Six houses have 5 pairs, and the loop makes 5 passes. Looking forward as well would meet every pair twice.

So this is the loop of step 1 with a different question, and with "is there any" in place of "are all": true at the first pair found, and false when the loop is through. For 0, 0, 1, 0, 0 and 0 the answer is false. For 0, 1, 1 and 0 it is true.

The question is about 1s. Two 0s side by side are neighbours too, and they are not what is asked for: one of this step's problems is a loop that takes them for a pair, to mend.

The same pairs can be met by looking forward, with numbers[i + 1] and a loop over 0..<numbers.count - 1. The answers are the same. Pick one direction and keep to it. This lesson looks back.

Step 4

The positions of each 0 whose neighbours are both 0, counting past the edge as 0

Now Harper's question, for every house at once: where can anyone sleep? In a quiet house with a quiet house on each side.

The problem also says what happens at the two ends: past the edge counts as 0. Past either end of the street, it is quiet.

Swift
/// The positions of each 0 whose neighbours are both 0. Past either end counts as 0.
/// `numbers` holds 0s and 1s, and at least two of them.
func zerosWithZeroNeighboursEndsApart(_ numbers: [Int]) -> [Int] {
    let last = numbers.count - 1
    var positions: [Int] = []
    if numbers[0] == 0 && numbers[1] == 0 {              // the first house: one neighbour
        positions.append(0)
    }
    for i in 1..<last {                                  // the middle: two neighbours
        if numbers[i] == 0 && numbers[i - 1] == 0 && numbers[i + 1] == 0 {
            positions.append(i)
        }
    }
    if numbers[last] == 0 && numbers[last - 1] == 0 {    // the last house: one neighbour
        positions.append(last)
    }
    return positions
}

What is new: the problem itself says what a neighbour who is not there counts as. Here that is 0, which is what the rule wants a neighbour to be. So the missing neighbour passes, and an end house has only its one real neighbour left to ask about. That is why the first if reads only numbers[1], and the last reads only numbers[last - 1].

The rest is the three pieces of step 2: the first house, the middle, the last house. They append in that order, so the positions come out smallest first. For 0, 0, 1, 0, 0 and 0 the answer is [0, 4, 5]. House 0 is in it because its one neighbour is quiet, and house 5 the same way.

What a problem says about its ends is part of the rule. Usually it says what this one says: past the edge counts as whatever lets the rule pass. If it does not say, ask.

Step 5

The same without special cases for the two ends

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

What is new: each side's question begins by asking whether there is a neighbour at all. i == 0 || numbers[i - 1] == 0 says: nobody on the left, or a 0 on the left. Either way the left side passes. That is step 4's rule, past the edge counts as 0, written into the test.

It is safe because of how || works. It works out its first half. When that is true the answer is already true, and || stops: the second half never runs. Swift's documentation promises this. So at house 0, where i == 0 is true, numbers[i - 1] is never read. At every other house there is a house on the left, and reading it is safe. The right side works the same way, with i == last and numbers[i + 1].

Now every house can be asked the same two questions, the end houses too. So the loop goes over numbers.indices, and three things are gone:

  • the two ifs for the end houses
  • the range typed by hand, and with it the range that cannot be made
  • the promise of two numbers

A street of one quiet house gives [0]: there is nobody on either side of it. One house with a drummer in it gives []. A street of no houses gives [], because the loop does not run.

The answers have not changed. The lesson's code ran the shape and step 4's function on every street of two to eight houses, 508 streets, and they agree on all of them.

The same move on another rule. Here are step 2's peaks again, the two ends included.

Swift
/// How many numbers are peaks: bigger than every neighbour they have.
func countOfPeaksInOneLoop(_ numbers: [Int]) -> Int {
    let last = numbers.count - 1
    var count = 0
    for i in numbers.indices {
        // each side: nobody there, or a smaller number
        let biggerThanLeft = i == 0 || numbers[i] > numbers[i - 1]
        let biggerThanRight = i == last || numbers[i] > numbers[i + 1]
        if biggerThanLeft && biggerThanRight {
            count += 1
        }
    }
    return count
}

What is new: only the rule. "Whatever lets the rule pass" depends on what the rule is. A peak has to be bigger than its neighbour, so a neighbour who is not there counts as smaller: nobody on that side, or a smaller number there. For 5, 1, 4, 2 and 9 the count is 3, as in step 2. One number on its own gives 1: it is bigger than every neighbour it has. No numbers give 0.

One last thing about the shape: it only looks. Houses 4 and 5 are both in its answer, and they are next door to each other. Each was judged on the street as it stood, and nothing was changed. The next lesson, "Take it as soon as you can", is where the loop starts to act on what it finds.

What goes wrong

Reading a neighbour who is not there. Start step 1's loop at 0, and at house 0 numbers[i - 1] asks for position -1. Run a loop that reads numbers[i + 1] on to the last of six houses, and it asks for position 6, when the last is 5. Swift does not hand back a 0 for a house that is not there. The program stops with "Index out of range".

A bug that hides. The read past the last house does not always happen. numbers[i] > numbers[i - 1] && numbers[i] > numbers[i + 1] is joined with &&, and && stops early too: when its first half is false, the second half never runs. So the loop that runs on to the last house reads past it only when the last number is bigger than the one before it. For 3, 8 and 2 it is not, and that loop answers 1, which is right. For 3, 8, 2 and 6 it is: the loop asks for position 4, the last is 3, and the program stops. A loop can pass the first test you give it and still be wrong at the end of the street.

A range that cannot be made. A range typed by hand must not end before it starts. For an array of none, 1..<numbers.count is 1..<0. 1..<numbers.count - 1 is 1..<0 for one number and 1..<-1 for none. The loop that looks forward, 0..<numbers.count - 1, is 0..<-1 for none. Each stops the program before the loop begins, with "Range requires lowerBound <= upperBound". "Loops and indexes" met the last of them. Either the problem promises enough numbers, or you ask first, or you write the shape, which has no range to make.

The two halves of || the wrong way round. numbers[i - 1] == 0 || i == 0 reads first and asks afterwards. At house 0 it asks for position -1, so the program stops at the first house of every street. Whether there is a neighbour comes first, always.

&& where || was meant. i > 0 && numbers[i - 1] == 0 says: there is a house on the left, and it is a 0. It never reads past the edge, so nothing stops. But at an end house nobody is there, so that side fails, and no end house is ever kept. For 0, 0, 1, 0, 0 and 0 it gives [4], where the answer is [0, 4, 5]. A wrong answer that looks like an answer is worse than a program that stops. Say the question aloud: nobody there, or a 0.

The wrong last position. Six houses are numbered 0 to 5, and numbers.count is 6. So i == numbers.count is never true: || goes on to its second half at every house, and at the last house it reads past the end. Write let last = numbers.count - 1 once, above the loop, and the two sides are mirror images: i == 0 and i == last.

Forgetting the house itself. The rule has three questions, and only two of them are about the neighbours. Leave out numbers[i] == 0 and the answer for the street is [0, 2, 4, 5]: house 2 is in it, drummer and all.

Reading the rule loosely. Not bigger is <=. With < in step 1, 2, 5, 5 and 9 is said to go up: the answer comes out true. And "a 1 next to another 1" is not "two neighbours the same". numbers[i] == numbers[i - 1] says true for 1, 0 and 0, where the two that sit together are 0s and the answer is false.

Say it back

1

A rule is about what is next door to position i. Which two positions does it read?

Show the answerHide the answer

i - 1 and i + 1: the house before and the house after.

2

Why does a loop that compares each number with the one before it start at 1?

Show the answerHide the answer

Position 0 has nobody before it. numbers[-1] does not hand back a 0. It stops the program.

3

A loop reads both numbers[i - 1] and numbers[i + 1]. Which positions may it visit, and what becomes of the two ends?

Show the answerHide the answer

From 1 to the one before the last: 1..<numbers.count - 1. The two end houses have one neighbour each. Either each gets an if of its own about that one neighbour, or the shape asks every house the same question.

4

What does i == 0 || numbers[i - 1] == 0 say, and why can it never read past the edge?

Show the answerHide the answer

Nobody on the left, or a 0 on the left. || runs its second half only when its first half is false, so when i is 0 the missing neighbour is never read.

5

What goes wrong with i > 0 && numbers[i - 1] == 0?

Show the answerHide the answer

Nothing stops, and the answer is wrong. It says there is a neighbour and it is a 0, so an end house fails on the side where nobody lives. Past the edge was meant to pass.

6

Which arrays stop for i in 1..<numbers.count - 1 before it begins, and why does the shape not mind them?

Show the answerHide the answer

An array of one number and an array of none: the range would end before it starts. The shape walks numbers.indices and types no range.

7

Why was the best neighbour Harper ever had one who did not exist?

Show the answerHide the answer

She had the end house. On one side there was nobody, and nobody passes every rule about neighbours: a house that is not there has no drummer in it. In code that is i == 0 || numbers[i - 1] == 0. Ask first whether there is a neighbour at all, and || never reads the one who is not there.

Practise

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

ProblemLevel
1Bigger than the one beforeEasy
2Equal is not biggerEasy
3Count the peaksEasy
4Two 1s side by sideEasy
5Quiet houses, each end on its ownEasy
6Quiet houses on any streetEasy
7House 0 is never restfulEasy

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.