Skip to the content

The top of the ridge

Problem

Casimiro guides groups along a mountain ridge, and before setting out he needs to know where the top is. The profile of the walk comes leg by leg: it climbs without a break up to the top and from there it only goes down. Two legs in a row are never at the same height.

You get the list of heights and you return the position of the highest leg, counting from 0. In 1, 4, 9, 7 and 3 the top is the 9, which sits at position 2.

The list always has at least one leg. The top may be the first leg, when the profile only goes down, or the last one, when it only climbs. Profiles go up to 100 legs.

You can't use max, Math.max, indexOf or the index method of Python lists: walking the whole profile is exactly what Casimiro wants to avoid. Idea: stand on the middle leg and compare it with the one after it. If the next one is higher, you are still climbing and the top is to the right. If it is lower, you are already going down, so the top is that leg or one of the ones behind it. That throws away half the list on every step, even though the heights don't come sorted.

Examples

  • The example

    [1, 4, 9, 7, 3] → 2

  • The top comes early

    [3, 8, 12, 20, 18, 11, 4, 1] → 3

  • The profile only climbs

    [2, 5, 7, 10] → 3

  • The profile only goes down

    [9, 6, 4, 1] → 0

  • Two legs, the first one higher

    [4, 1] → 0

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def summit(heights):
    pass

JavaScript

function summit(heights) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. It is free and you do not need an account to start.

More O(log n) challenges

See all challenges →