Given an array arr[] of N positive integers and two positive integers S and K, the task is to reach the position of the array whose value is K from index S. We can only move from current index i to index (i + arr[i]) or (i – arr[i]). If there is a way to reach the position of the array whose value is K then print “Yes” else print “No”.
Examples:
Input: arr[] = {4, 2, 3, 0, 3, 1, 2}, S = 5, K = 0.
Output: Yes
Explanation:
Initially we are standing at index 5 that is element 1 hence we can move one step forward or backward. Therefore, all possible ways to reach at index 3 with value 0 are:
index 5 -> index 4 -> index 1 -> index 3
index 5 -> index 6 -> index 4 -> index 1 -> index 3. Since it is possible to reach index 3 our output is yes.Input: arr[] = {0, 3, 2, 1, 2}, S = 2, K = 3
Output: No
Explanation:
There is no way to reach index 1 with value 3.
Method 1 – Using BFS The Breadth-first search(BFS) approach is discussed below:
- Consider start index S as the source node and insert it into the queue.
- While the queue is not empty do the following:
- Pop the element from the top of the queue say temp.
- If temp is already visited or it is array out of bound index then, go to step 1.
- Else mark it as visited.
- Now if temp is the index of the array whose value is K, then print “Yes”.
- Else take two possible destinations from temp to (temp + arr[temp]), (temp – arr[temp]) and push it into the queue.
- If the index with value K is not reached after the above steps then print “No”.
Below is the implementation of the above approach:
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // BFS approach to check if traversal // is possible or not bool check(int arr[], int& s_start, int start, bool visited[], int size, int K) { queue<int> q; // Push start index into queue q.push(start); // Until queue is not empty while (!q.empty()) { // Top element of queue int front = q.front(); // Pop the topmost element q.pop(); // mark as visited visited[front] = true; if (arr[front] == K && front != s_start) { return true; } // Check for i + arr[i] if (front + arr[front] >= 0 && front + arr[front] < size && visited[front + arr[front]] == false) { q.push(front + arr[front]); } // Check for i - arr[i] if (front - arr[front] >= 0 && front - arr[front] < size && visited[front - arr[front]] == false) { q.push(front - arr[front]); } } return false; } // Function to check if index with value // K can be reached or not void solve(int arr[], int n, int start, int K) { // Initialize visited array bool visited[n] = { false }; // BFS Traversal bool ans = check(arr, start, start, visited, n, K); // Print the result if (ans) cout << "Yes"; else cout << "No"; } // Driver Code int main() { // Given array arr[] int arr[] = { 3, 0, 2, 1, 2 }; // Given start and end int start = 2; int K = 0; int N = sizeof(arr) / sizeof(arr[0]); // Function Call solve(arr, N, start, K); return 0; } |
No
Time Complexity: O(N)
Auxiliary Space: O(N)
Method 2 – Using DFS: The Depth-first search(DFS) approach is discussed below:
- Initialize an array visited[] to mark visited vertex as true.
- Start with the start index S and explore other index depth-wise using recursion.
- In each recursive call, we check if that index is valid or previously not visited. If not so, we return false.
- Else if that index value is K, we return true.
- Else mark that index as visited and process recursively for i + arr[i] and i – arr[i] from current index i.
- If any of the recursive calls return true, this means that we reach to index with value K is possible and we print “Yes” Else print “No”.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // DFS approach to check if traversal // is possible or not bool check(int arr[], int& s_start, int start, bool visited[], int size, int K) { // Base cases if (start < 0 || start >= size || visited[start]) { return false; } // Check if start index value K if (arr[start] == K && start != s_start) { return true; } // Mark as visited visited[start] = true; // Check for both i + arr[i] // and i - arr[i] recursively return (check(arr, s_start, start + arr[start], visited, size, K) || check(arr, s_start, start - arr[start], visited, size, K)); } // Function to check if index with value // K can be reached or not void solve(int arr[], int n, int start, int K) { // Initialize visited array bool visited[n] = { false }; // DFS Traversal bool ans = check(arr, start, start, visited, n, K); // Print the result if (ans) cout << "Yes"; else cout << "No"; } // Driver Code int main() { // Given array arr[] int arr[] = { 3, 0, 2, 1, 2 }; // Given start and end int start = 2; int K = 0; int N = sizeof(arr) / sizeof(arr[0]); // Function Call solve(arr, N, start, K); return 0; } |
Java
// Java program for the above approach import java.util.Arrays; class GFG{ // DFS approach to check if traversal // is possible or not public static boolean check(int[] arr, int s_start, int start, boolean[] visited, int size, int K) { // Base cases if (start < 0 || start >= size || visited[start]) { return false; } // Check if start index value K if (arr[start] == K && start != s_start) { return true; } // Mark as visited visited[start] = true; // Check for both i + arr[i] // and i - arr[i] recursively return (check(arr, s_start, start + arr[start], visited, size, K) || check(arr, s_start, start - arr[start], visited, size, K)); } // Function to check if index with value // K can be reached or not public static void solve(int[] arr, int n, int start, int K) { // Initialize visited array boolean[] visited = new boolean[n]; Arrays.fill(visited, false); // DFS Traversal boolean ans = check(arr, start, start, visited, n, K); // Print the result if (ans) System.out.print("Yes"); else System.out.print("No"); } // Driver code public static void main(String[] args) { // Given array arr[] int arr[] = { 3, 0, 2, 1, 2 }; // Given start and end int start = 2; int K = 0; int N = arr.length; // Function call solve(arr, N, start, K); } } // This code is contributed by divyeshrabadiya07 |
C#
// C# program for the above approach using System; class GFG{ // DFS approach to check if traversal // is possible or not public static bool check(int[] arr, int s_start, int start, bool[] visited, int size, int K) { // Base cases if (start < 0 || start >= size|| visited[start]) { return false; } // Check if start index value K if (arr[start] == K && start != s_start) { return true; } // Mark as visited visited[start] = true; // Check for both i + arr[i] // and i - arr[i] recursively return (check(arr, s_start, start + arr[start], visited, size, K) || check(arr, s_start, start - arr[start], visited, size, K)); } // Function to check if index with value // K can be reached or not public static void solve(int[] arr, int n, int start, int K) { // Initialize visited array bool[] visited = new bool[n]; // DFS Traversal bool ans = check(arr, start, start, visited, n, K); // Print the result if (ans) Console.Write("Yes"); else Console.Write("No"); } // Driver code public static void Main(String[] args) { // Given array []arr int []arr = { 3, 0, 2, 1, 2 }; // Given start and end int start = 2; int K = 0; int N = arr.Length; // Function call solve(arr, N, start, K); } } // This code is contributed by Princi Singh |
No
Time Complexity: O(N)
Auxiliary Space: O(N)
Recommended Posts:
- Check if every index i has an index j such that sum of elements in both directions are equal
- Minimum index i such that all the elements from index i to given index are equal
- Find start and ending index of an element in an unsorted array
- Queries for number of distinct elements from a given index till last index in an array
- Count of contiguous subarrays possible for every index by including the element at that index
- Number of permutations such that sum of elements at odd index and even index are equal
- Difference between Inverted Index and Forward Index
- Minimum cost to reach end of array array when a maximum jump of K index is allowed
- Rearrange array such that even index elements are smaller and odd index elements are greater
- Sort Array such that smallest is at 0th index and next smallest it at last index and so on
- Count ways to reach end from start stone with at most K jumps at each step
- Minimum steps to reach end from start by performing multiplication and mod operations with array elements
- Smallest index such that there are no 0 or 1 to its right
- Even numbers at even index and odd numbers at odd index
- Equilibrium index of an array
- Why array index starts from zero ?
- Sum of the elements from index L to R in an array when arr[i] = i * (-1)^i
- Number with set bits only between L-th and R-th index
- Longest Subsequence where index of next element is arr[arr[i] + i]
- Find the index of first 1 in a sorted array of 0's and 1's
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


