749. River Crossing Frog

A frog wants to cross a river using stones whose positions (distances from the bank, in units) are given in stones. The list may be unsorted and may repeat a position; a repeated position is still one stone. The frog starts on the stone with the smallest position and wants to reach the one with the largest.

The frog only jumps forward and only lands on stones. Its first jump must be exactly 1 unit. If its previous jump was k units, the next one must be k-1, k or k+1 units, and always at least 1. Return true if the frog can reach the farthest stone, otherwise false. With just one distinct stone the frog is already there, so return true.

Aim for time O(n^2) and space O(n^2), where n is the number of stones.

Example 1

Input:
stones = [2,3,5,8,12]
Output:
true
Explanation:

The jumps 1, 2, 3 and 4 land on 3, 5, 8 and 12 in turn, each size following the rule, so the frog reaches 12.

Example 2

Input:
stones = [3,4,6,10,11]
Output:
false
Explanation:

After 3, 4, 6 (jumps 1, 2) the next jump is at most 3, which reaches 9 at best, and there is no stone there: false.

Example 3

Input:
stones = [7,7]
Output:
true
Explanation:

Both entries are the same stone, so the frog is already at the farthest stone: true.

Constraints

1 ≤ stones.length ≤ 5000

0 ≤ stones[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n^2)
Space
O(n^2)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…