Jump Game III — LeetCode 1306 Python Solution
- Problem
- #1306
- Pattern
- Breadth-First Search
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach any index with value 0.
Example
- Input
- arr = [4,2,3,0,3,1,2], start = 5
- Output
- true
- Explanation
- All possible ways to reach at index 3 with value 0 are:
Python solution
class Solution:
def canReach(self, arr: List[int], start: int) -> bool:
q = deque([start])
while q:
i = q.popleft()
if arr[i] == 0:
return True
x = arr[i]
arr[i] = -1
for j in (i + x, i - x):
if 0 <= j < len(arr) and arr[j] >= 0:
q.append(j)
return FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Breadth-First Search
Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 1306. Jump Game III is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.
The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1306. Jump Game III?
- LeetCode 1306. Jump Game III is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1306. Jump Game III?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1306. Jump Game III?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1306. Jump Game III cover?
- LeetCode 1306. Jump Game III is tagged Depth-First Search, Breadth-First Search and Array on LeetCode.