Given an array arr[] of N positive integers and a number S, the task is to reach the end of the array 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 end of the array then print “Yes” else print “No”.
Examples:
Input: arr[] = {4, 1, 3, 2, 5}, S = 1
Output: Yes
Explanation:
initial position: arr[S] = arr[1] = 1.
Jumps to reach the end: 1 -> 4 -> 5
Hence end has been reached.
Input: arr[] = {2, 1, 4, 5}, S = 2
Output: No
Explanation:
initial position: arr[S] = arr[2] = 2.
Possible Jumps to reach the end: 4 -> (index 7) or 4 -> (index -2)
Since both are out of bounds, Hence end can’t be reached.
Approach 1: This problem can be solved using Breadth First Search. Below are the steps:
- 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 last index of the array, 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 end of the array is not reached after the above steps then print “No”.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void solve( int arr[], int n, int start)
{
queue< int > q;
bool visited[n] = { false };
bool reached = false ;
q.push(start);
while (!q.empty()) {
int temp = q.front();
q.pop();
if (visited[temp] == true )
continue ;
visited[temp] = true ;
if (temp == n - 1) {
reached = true ;
break ;
}
if (temp + arr[temp] < n) {
q.push(temp + arr[temp]);
}
if (temp - arr[temp] >= 0) {
q.push(temp - arr[temp]);
}
}
if (reached == true ) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
}
int main()
{
int arr[] = { 4, 1, 3, 2, 5 };
int S = 1;
int N = sizeof (arr) / sizeof (arr[0]);
solve(arr, N, S);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void solve( int arr[], int n, int start)
{
Queue<Integer> q = new LinkedList<>();
boolean []visited = new boolean [n];
boolean reached = false ;
q.add(start);
while (!q.isEmpty())
{
int temp = q.peek();
q.remove();
if (visited[temp] == true )
continue ;
visited[temp] = true ;
if (temp == n - 1 )
{
reached = true ;
break ;
}
if (temp + arr[temp] < n)
{
q.add(temp + arr[temp]);
}
if (temp - arr[temp] >= 0 )
{
q.add(temp - arr[temp]);
}
}
if (reached == true )
{
System.out.print( "Yes" );
}
else
{
System.out.print( "No" );
}
}
public static void main(String[] args)
{
int arr[] = { 4 , 1 , 3 , 2 , 5 };
int S = 1 ;
int N = arr.length;
solve(arr, N, S);
}
}
|
Python3
from queue import Queue
def solve(arr, n, start):
q = Queue()
visited = [ False ] * n
reached = False
q.put(start);
while ( not q.empty()):
temp = q.get()
if (visited[temp] = = True ):
continue
visited[temp] = True
if (temp = = n - 1 ):
reached = True
break
if (temp + arr[temp] < n):
q.put(temp + arr[temp])
if (temp - arr[temp] > = 0 ):
q.put(temp - arr[temp])
if (reached = = True ):
print ( "Yes" )
else :
print ( "No" )
if __name__ = = '__main__' :
arr = [ 4 , 1 , 3 , 2 , 5 ]
S = 1
N = len (arr)
solve(arr, N, S)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void solve( int []arr, int n,
int start)
{
Queue< int > q = new Queue< int >();
bool []visited = new bool [n];
bool reached = false ;
q.Enqueue(start);
while (q.Count != 0)
{
int temp = q.Peek();
q.Dequeue();
if (visited[temp] == true )
continue ;
visited[temp] = true ;
if (temp == n - 1)
{
reached = true ;
break ;
}
if (temp + arr[temp] < n)
{
q.Enqueue(temp + arr[temp]);
}
if (temp - arr[temp] >= 0)
{
q.Enqueue(temp - arr[temp]);
}
}
if (reached == true )
{
Console.Write( "Yes" );
}
else
{
Console.Write( "No" );
}
}
public static void Main(String[] args)
{
int []arr = { 4, 1, 3, 2, 5 };
int S = 1;
int N = arr.Length;
solve(arr, N, S);
}
}
|
Javascript
<script>
function solve(arr, n, start)
{
let q = [];
let visited = new Array(n);
visited.fill( false );
let reached = false ;
q.push(start);
while (q.length > 0)
{
let temp = q[0];
q.shift();
if (visited[temp] == true )
continue ;
visited[temp] = true ;
if (temp == n - 1)
{
reached = true ;
break ;
}
if (temp + arr[temp] < n)
{
q.push(temp + arr[temp]);
}
if (temp - arr[temp] >= 0)
{
q.push(temp - arr[temp]);
}
}
if (reached == true )
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
}
let arr = [ 4, 1, 3, 2, 5 ];
let S = 1;
let N = arr.length;
solve(arr, N, S);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Recursive approach:
Approach:
In this approach, we recursively check if we can reach the end of the array by making valid jumps from the current position.
Define a function can_reach_end that takes an array arr and a starting position pos.
Check the base case: If the current position is the last index of the array, then we can reach the end, so return True.
Find the maximum number of steps we can take from the current position without going out of bounds, i.e., max_jump.
Loop through all possible next positions, starting from pos + 1 up to max_jump.
For each next position, recursively call can_reach_end with the next position as the new starting position.
If any of the recursive calls return True, then we can reach the end, so return True.
If we can’t reach the end from any of the possible jumps, return False.
Java
import java.io.*;
public class GFG
{
public static boolean canReachEnd( int [] arr, int pos) {
if (pos == arr.length - 1 ) {
return true ;
}
int maxJump = Math.min(pos + arr[pos], arr.length - 1 );
for ( int nextPos = pos + 1 ; nextPos <= maxJump; nextPos++) {
if (canReachEnd(arr, nextPos)) {
return true ;
}
}
return false ;
}
public static void main(String[] args) {
int [] arr = { 4 , 1 , 3 , 2 , 5 };
int startPos = 1 ;
if (canReachEnd(arr, startPos)) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
}
}
|
Python3
def can_reach_end(arr, pos):
if pos = = len (arr) - 1 :
return True
max_jump = min (pos + arr[pos], len (arr) - 1 )
for next_pos in range (pos + 1 , max_jump + 1 ):
if can_reach_end(arr, next_pos):
return True
return False
arr = [ 4 , 1 , 3 , 2 , 5 ]
start_pos = 1
if can_reach_end(arr, start_pos):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
public class GFG
{
public static bool CanReachEnd( int [] arr, int pos)
{
if (pos == arr.Length - 1)
{
return true ;
}
int maxJump = Math.Min(pos + arr[pos], arr.Length - 1);
for ( int nextPos = pos + 1; nextPos <= maxJump; nextPos++)
{
if (CanReachEnd(arr, nextPos))
{
return true ;
}
}
return false ;
}
public static void Main( string [] args)
{
int [] arr = { 4, 1, 3, 2, 5 };
int startPos = 1;
if (CanReachEnd(arr, startPos))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
function canReachEnd(arr, pos) {
if (pos == arr.length - 1) {
return true ;
}
let maxJump = Math.min(pos + arr[pos], arr.length - 1);
for (let nextPos = pos + 1; nextPos <= maxJump; nextPos++) {
if (canReachEnd(arr, nextPos)) {
return true ;
}
}
return false ;
}
let arr = [4, 1, 3, 2, 5];
let startPos = 1;
if (canReachEnd(arr, startPos)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
|
Time Complexity: O(2^n) where n is the length of the array.
Space Complexity: O(n) where n is the length of the array.