#1871
Jump Game VII
MediumStringDynamic ProgrammingSliding WindowPrefix SumSliding WindowBreadth-First Search (BFS)
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a sliding window approach to keep track of the farthest index we can reach. This reduces unnecessary checks and efficiently determines if we can reach the end.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a variable to track the farthest index we can reach.
- 2Step 2: Iterate through the string, updating the farthest index based on the current index and the jump limits.
- 3Step 3: If at any point the farthest index reaches or exceeds the last index, return true.
- 4Step 4: If the loop completes without reaching the last index, return false.
solution.py9 lines
1def canReach(s, minJump, maxJump):
2 n = len(s)
3 farthest = 0
4 for i in range(n):
5 if i > farthest:
6 return False
7 if s[i] == '0' and i + minJump <= n - 1:
8 farthest = max(farthest, i + maxJump)
9 return farthest >= n - 1ℹ
Complexity note: This complexity is linear because we only traverse the string once, updating the farthest reachable index without nested loops.
- 1Understanding the jump constraints is crucial for determining reachable indices.
- 2Using a sliding window approach can significantly reduce the number of checks needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.