#403
Frog Jump
HardArrayDynamic ProgrammingDynamic ProgrammingHash MapRecursive Backtracking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal approach uses dynamic programming with a hashmap to store reachable states. This avoids redundant calculations and allows us to efficiently check if the frog can reach the last stone.
⚙️
Algorithm
4 steps- 1Step 1: Create a hashmap to store reachable positions and their corresponding jump sizes.
- 2Step 2: Iterate through each stone and for each stone, check if the frog can jump to the next stones using the allowed jump sizes.
- 3Step 3: Update the hashmap with new reachable positions and their jump sizes.
- 4Step 4: At the end, check if the last stone is reachable.
solution.py9 lines
1def canCross(stones):
2 dp = {stone: set() for stone in stones}
3 dp[0].add(0)
4 for stone in stones:
5 for jump in dp[stone]:
6 for next_jump in [jump - 1, jump, jump + 1]:
7 if next_jump > 0 and stone + next_jump in dp:
8 dp[stone + next_jump].add(next_jump)
9 return len(dp[stones[-1]]) > 0ℹ
Complexity note: The time complexity remains O(n²) due to the nested loops, but we use a hashmap to store reachable states, which optimizes space usage and avoids recalculating paths.
- 1The frog can only jump forward, which limits the problem's complexity.
- 2Using a hashmap to track reachable positions helps avoid redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.