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 to the village at the bottom. An alert starts at tower 0 and must reach the last tower. Each tower can forward the alert down the valley, but only so far: tower i can send it to any of the next reach[i] towers.

Some transmitters are weak, and a few are broken (reach[i] = 0), though a broken tower can still receive. Before the storm season, the rescue team wants to know whether an alert from the top can 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 the alert from tower 0 to tower reach.length - 1, and false otherwise.

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

canReachLastTower(reach: int[]) → bool

Examples

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

Tower 0 can reach towers 1, 2 and 3. Tower 2 can reach 3 and 4. Tower 4 reaches 5, the last one. So 0 → 2 → 4 → 5 works. Towers 1 and 3 are broken, but you do not have to use them.

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 2. Tower 2 is broken. Nothing ever gets past tower 2, so the strong tower 3 never hears the alert.

Constraints

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

Explore every chain: from tower 0 try every tower it can reach, then every tower those can reach, and so on, with a search that marks 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, so it is O(n²) in the worst case: about 50 million steps for 10,000 strong towers.

The search tracks which towers are reachable, one by one. 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