Hut-to-Hut Trek

MediumgreedyAlso known as Jump Game II

You are planning a long trek along a trail with mountain huts, numbered from 0 at the trailhead to the last hut at the end. You must sleep in a hut every night. The guidebook says, for each hut, how far you can walk in one day starting from there: from hut i, a day's walk can take you to any of the next reach[i] huts. Steep sections give small numbers, easy valleys big ones.

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

Day 1: hut 0 to hut 1. Day 2: hut 1 can reach up to hut 5, the last one. Walking as far as possible on day 1 (to hut 2) is a trap: from there the huts only allow one step a day, and the trek takes 4 days.

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

Day 1: hut 0 to hut 3. Day 2: hut 3 reaches huts 4, 5 and 6, and 6 is the last. One day is not enough, because hut 0 reaches only up to 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

Treat it as a shortest path: a breadth-first search from hut 0, where each hut links to every hut within its reach. That is correct, but hut i has up to reach[i] links, so the search can look at O(n²) links: about 50 million for 10,000 huts with long reaches.

Another tempting idea, "each day walk as far as you can", 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