VOOZH about

URL: https://www.geeksforgeeks.org/dsa/jump-game-iii-problem/

⇱ Jump Game III Problem - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Jump Game III Problem

Last Updated : 23 Jul, 2025

Given an array arr[] of non-negative integers size N, the task is to start from index X and check if we can reach any index with value 0. For any index i, we can jump to i + arr[i] or i - arr[i].

Note: We cannot jump outside the array at any time.

Examples:

Input: arr[] = {4, 2, 3, 0, 3, 1, 2}, X = 5
Output: true
Explanation: It is possible to reach index 3 from index 5.

  • Start from index 5, arr[5] = 1 so jump to index 4.
  • From index 4, arr[4] = 3 so jump to index 1.
  • From index 1, arr[1] = 2 so jump to index 3.

Input: arr[] = {3, 0, 2, 1, 2}, X = 2
Output: false
Explanation: It is impossible to reach any index with value 0.

Approach: To solve the problem, follow the below idea:

The problem can be solved using Breadth-First-Search. Maintain a dist[] array which stores the minimum jumps to reach any index. We can start from the index X and check for index X + arr[X] and X - arr[X]. If the distance to reach those indices are minimum so far, then update the distance and push those indices to the queue. We continue to traverse the array arr[] till q does not become empty. Now, we can simply traverse over all the indices and check for any index with value 0 with distance != INF. If such an index is found, return true else return false.

Step-by-step algorithm:

  • Maintain a distance array dist[] which stores minimum jumps to store minimum jumps to reach any index.
  • Maintain a queue to run BFS starting from index X.
  • Initialize dist[X] = 0 and push X to the queue.
  • While queue is not empty,
    • Pop the front element, say idx from the queue.
    • Find the index left = idx - arr[idx] and check if the distance to reach the left is greater than current distance. If yes, then update dist[left] and push the left index to the queue.
    • Find the index right = idx + arr[idx] and check if the distance to reach the right is greater than current distance. If yes, then update dist[right] and push the right index to the queue.
  • After iterating over all the indices and check for any index with value 0 with distance != INF. If such an index is found, return true else return false.

Below is the implementation of the above approach:


Output
1

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment
Article Tags: