![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
1
Time Complexity: O(N)
Auxiliary Space: O(N)