Jump Game III — LeetCode 1306 Python Solution

MediumDepth-First SearchBreadth-First SearchArray
Problem
#1306
Reading time
3 min

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

Python
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 False

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview