Relay Towers Down the Valley

EasygreedyAlso known as Jump Game

A mountain valley has a row of radio relay towers, numbered from 0 at the top down to the village. An alert starts at tower 0 and must reach the last tower. Tower i can forward it to any of the next reach[i] towers.

A few towers are broken (reach[i] = 0), though they can still receive. Before storm season, the rescue team wants to know: can an alert from the top reach the village at all?

Your task

Write canReachLastTower(reach). From tower i, the alert can go to any tower j with i < j ≤ i + reach[i]. Return true if some chain of forwards takes it from tower 0 to tower reach.length - 1, otherwise false.

With a single tower, the alert is already at the last tower: return true.

canReachLastTower(reach: int[]) → bool

Examples

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

Tower 0 reaches towers 1, 2 and 3. Tower 2 reaches 3 and 4. Tower 4 reaches 5, the last one. So 0 → 2 → 4 → 5 works, without using the broken towers 1 and 3.

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

From tower 0 the alert reaches 1 or 2. Tower 1 reaches only tower 2, and tower 2 is broken, so nothing gets past tower 2 and the strong tower 3 never hears the alert.

Constraints

  • 1 ≤ reach.length ≤ 10,000
  • 0 ≤ reach[i] ≤ 100,000
Start with brute force

Search every chain from tower 0, marking visited towers. Without marking, the number of chains grows exponentially. With marking it is correct, but each tower may look at up to reach[i] others: O(n²) in the worst case, about 50 million steps for 10,000 strong towers.

The search tracks which towers are reachable. You only need to know how far the reachable block extends.

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