Skip to the content

Beach umbrellas

Problem

"Nobody stays in the sun," says the lifeguard. Towels are spread along the beach, and each umbrella shades a stretch of fixed length; she wants them all covered with as few umbrellas as possible.

Write a function that takes towels, the position of each towel in meters (integers from 0 up, in any order, with repeats; the list may be empty), and span, an integer from 0 up. An umbrella that starts at meter p covers every towel from p to p + span, both ends included, and it can start at any meter. Return the fewest umbrellas, as an integer; with no towels, 0.

With [1, 2, 8, 4, 12] and span 3: one from 1 to 4 covers 1, 2 and 4; another covers the 8 and another the 12. That's 3.

Examples

  • The example

    [1, 2, 8, 4, 12], 3 → 3

  • Right at the edge of the shade

    [0, 5, 10, 15], 5 → 2

  • Towels on top of each other

    [3, 3, 3, 7], 2 → 2

  • A single towel

    [7], 3 → 1

  • A lone towel at meter 0

    [0, 10], 3 → 2

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

You start with this

Python

def umbrellas(towels, span):
    pass

JavaScript

function umbrellas(towels, span) {
}
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 log n) challenges

See all challenges →