Skip to the content

The antennas that see each other

Problem

Four thousand meters up, on a ridge in the Andes, Tomás Quispe looks after a row of relay antennas. Two antennas talk directly if nothing blocks the line: every antenna standing between them must be shorter than the shorter of the two; one in the middle exactly as tall as that one already blocks it. Two antennas side by side, with nothing between, always talk.

Write a function that takes heights, the antenna heights in order along the ridge (whole numbers greater than 0; there may be repeats and the list may be empty). Return a whole number: how many pairs of antennas talk directly. Each pair counts once. Empty or with a single antenna, return 0.

With [4, 2, 3, 1, 5], the 4 side-by-side pairs count. Also, the 4 and the 3 see each other over the 2; the 3 and the 5, over the 1; and the 4 and the 5, over 2, 3 and 1. Neither the 4 nor the 2 sees the 1: the 3 is not shorter than 1. Nor do the 2 and the 5, because the 3 blocks them. You return 4 + 3 = 7.

Examples

  • The example

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

  • Three the same

    [3, 3, 3] → 2

  • Going up

    [1, 2, 3, 4] → 3

  • A valley with a flat floor

    [5, 1, 1, 5] → 4

  • Seven antennas

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

  • Only two

    [3, 3] → 1

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

You start with this

Python

def links(heights):
    pass

JavaScript

function links(heights) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n²) challenges

See all challenges →