#1306
Jump Game III
MediumArrayDepth-First SearchBreadth-First SearchBFSGraph TraversalArray
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 a Breadth-First Search (BFS) to explore all possible jumps iteratively. This ensures that we efficiently check each index without revisiting, leading to a faster solution.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a queue and add the starting index to it.
- 2Step 2: Use a set to keep track of visited indices to avoid cycles.
- 3Step 3: While the queue is not empty, dequeue an index and check if its value is 0.
- 4Step 4: Calculate the next possible indices to jump to (i + arr[i] and i - arr[i]).
- 5Step 5: If the next index is valid and not visited, add it to the queue and mark it as visited.
solution.py19 lines
1# Full working Python code
2
3from collections import deque
4
5def canReach(arr, start):
6 queue = deque([start])
7 visited = set()
8 while queue:
9 index = queue.popleft()
10 if arr[index] == 0:
11 return True
12 visited.add(index)
13 next_index = index + arr[index]
14 if next_index < len(arr) and next_index not in visited:
15 queue.append(next_index)
16 next_index = index - arr[index]
17 if next_index >= 0 and next_index not in visited:
18 queue.append(next_index)
19 return Falseℹ
Complexity note: The BFS approach processes each index at most once, leading to O(n) time complexity. The space complexity is O(n) due to the queue and visited set.
- 1BFS is more efficient than DFS for this problem due to its iterative nature and ability to avoid deep recursion.
- 2Visited tracking is crucial to prevent infinite loops.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.