Hut-to-Hut Trek

MediumgreedyAlso known as Jump Game II

You are planning a trek along a trail of mountain huts, numbered from 0 at the trailhead to the last hut, sleeping in a hut every night. The guidebook says how far a day's walk goes from each hut: from hut i, you can reach any of the next reach[i] huts. You want to finish in as few days as possible.

Your task

Write fewestDays(reach). In one day you may go from hut i to any hut j with i < j ≤ i + reach[i]. Return the fewest days needed to get from hut 0 to hut reach.length - 1.

The last hut is always reachable. If there is only one hut, you are already there: return 0.

fewestDays(reach: int[]) → int

Examples

Example 1
Input
reach = [2, 4, 1, 1, 1, 1]
Output
2
Why

On day 1 you walk from hut 0 to hut 1, and on day 2 you walk from hut 1 to hut 5, which is the last hut. Walking as far as possible on day 1 (to hut 2) is a trap: from there each day goes one hut, and the trek takes 4 days.

Example 2
Input
reach = [3, 1, 1, 3, 0, 2, 0]
Output
2
Why

On day 1 you walk from hut 0 to hut 3, and on day 2 you walk from hut 3 to hut 6, which is the last hut. One day is not enough, because hut 0 reaches only as far as hut 3.

Constraints

  • 1 ≤ reach.length ≤ 10,000
  • 0 ≤ reach[i] ≤ 100,000
  • The last hut can always be reached from hut 0.
Start with brute force

Breadth-first search from hut 0, linking each hut to every hut in its reach, is correct, but can look at O(n²) links: about 50 million for 10,000 huts with long reaches. "Walk as far as you can each day" is fast but wrong, as the first example shows.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code