Can the Frog Reach the Last Lily Pad?
Solve this ProblemA frog stands on the first of a row of lily pads. Each pad has a number: the longest hop the frog can make forward from that pad. From pad i it may hop to any pad from i + 1 up to i + hops[i]. Decide whether the frog can reach the last pad.
Working out, pad by pad, which pads are reachable by looking back at every earlier pad is quadratic. A simple greedy insight does it in one pass: the reachable pads always form a solid stretch starting at pad 0, so it is enough to remember how far that stretch extends.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ hops.length ≤ 15 and 0 ≤ hops[i] ≤ 8; hops[i] is the longest hop the frog can make from pad i - ◆
The frog starts on pad 0. From pad i it may hop forward to any pad from i + 1 up to i + hops[i] — any distance in that range, not only the maximum - ◆
A pad with hops[i] = 0 lets the frog go nowhere. Return true if the frog can reach the last pad, otherwise false
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Work Out Which Pads Are Reachable One by One
BruteBuild a table where reachable[p] says whether the frog can get to pad p. Pad 0 is reachable. For each later pad, look back at every earlier pad: if some pad is reachable and its longest hop reaches at least pad p, then p is reachable. The answer is reachable[n − 1]. It is correct, but every pad is compared with every earlier pad.
O(n²)O(n)1class Solution {
2 public boolean canReachLastPad(int[] hops) {
3 int n = hops.length;
4 boolean[] reachable = new boolean[n];
5 reachable[0] = true;
6 for (int pad = 1; pad < n; pad++) {
7 for (int from = 0; from < pad; from++) {
8 if (reachable[from] && from + hops[from] >= pad) {
9 reachable[pad] = true;
10 break;
11 }
12 }
13 }
14 return reachable[n - 1];
15 }
16}Optimal — Track the Farthest Pad Any Reachable Pad Can Reach
OptimalThe set of reachable pads is always a solid stretch from pad 0 up to some farthest pad — if the frog can reach pad p, it can reach every pad before p on the way (it can hop shorter distances). So just remember that farthest reachable pad. Walk the pads in order: if you arrive at a pad beyond the farthest reachable one, the frog is stranded — return false. Otherwise extend the farthest reach with pad + hops[pad]. If the walk finishes, the last pad was reachable.
O(n)O(1)1class Solution {
2 public boolean canReachLastPad(int[] hops) {
3 int farthest = 0;
4 for (int pad = 0; pad < hops.length; pad++) {
5 if (pad > farthest) return false;
6 farthest = Math.max(farthest, pad + hops[pad]);
7 }
8 return true;
9 }
10}