Frog Jump — LeetCode 403 Python Solution
HardArrayDynamic Programming
- Problem
- #403
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone.
Example
- Input
- stones = [0,1,3,5,6,8,12,17]
- Output
- true
- Explanation
- The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.
Python solution
Python
class Solution:
def canCross(self, stones: List[int]) -> bool:
@cache
def dfs(i, k):
if i == n - 1:
return True
for j in range(k - 1, k + 2):
if j > 0 and stones[i] + j in pos and dfs(pos[stones[i] + j], j):
return True
return False
n = len(stones)
pos = {s: i for i, s in enumerate(stones)}
return dfs(0, 0)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n^2) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 403. Frog Jump is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 403. Frog Jump?
- LeetCode 403. Frog Jump is rated Hard on LeetCode.
- What is the time complexity of LeetCode 403. Frog Jump?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 403. Frog Jump?
- The Python solution on this page uses O(n^2) auxiliary space.
- What topics does LeetCode 403. Frog Jump cover?
- LeetCode 403. Frog Jump is tagged Array and Dynamic Programming on LeetCode.