Check if the end of the Array can be reached from a given position
Last Updated :
15 Jul, 2025
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++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if we can reach to
// the end of the arr[] with possible moves
void solve(int arr[], int n, int start)
{
// Queue to perform BFS
queue<int> q;
// Initially all nodes(index)
// are not visited.
bool visited[n] = { false };
// Initially the end of
// the array is not reached
bool reached = false;
// Push start index in queue
q.push(start);
// Until queue becomes empty
while (!q.empty()) {
// Get the top element
int temp = q.front();
// Delete popped element
q.pop();
// If the index is already
// visited. No need to
// traverse it again.
if (visited[temp] == true)
continue;
// Mark temp as visited
// if not
visited[temp] = true;
if (temp == n - 1) {
// If reached at the end
// of the array then break
reached = true;
break;
}
// If temp + arr[temp] and
// temp - arr[temp] are in
// the index of array
if (temp + arr[temp] < n) {
q.push(temp + arr[temp]);
}
if (temp - arr[temp] >= 0) {
q.push(temp - arr[temp]);
}
}
// If reaches the end of the array,
// Print "Yes"
if (reached == true) {
cout << "Yes";
}
// Else print "No"
else {
cout << "No";
}
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 4, 1, 3, 2, 5 };
// Starting index
int S = 1;
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
solve(arr, N, S);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to check if we can reach to
// the end of the arr[] with possible moves
static void solve(int arr[], int n, int start)
{
// Queue to perform BFS
Queue<Integer> q = new LinkedList<>();
// Initially all nodes(index)
// are not visited.
boolean []visited = new boolean[n];
// Initially the end of
// the array is not reached
boolean reached = false;
// Push start index in queue
q.add(start);
// Until queue becomes empty
while (!q.isEmpty())
{
// Get the top element
int temp = q.peek();
// Delete popped element
q.remove();
// If the index is already
// visited. No need to
// traverse it again.
if (visited[temp] == true)
continue;
// Mark temp as visited
// if not
visited[temp] = true;
if (temp == n - 1)
{
// If reached at the end
// of the array then break
reached = true;
break;
}
// If temp + arr[temp] and
// temp - arr[temp] are in
// the index of array
if (temp + arr[temp] < n)
{
q.add(temp + arr[temp]);
}
if (temp - arr[temp] >= 0)
{
q.add(temp - arr[temp]);
}
}
// If reaches the end of the array,
// Print "Yes"
if (reached == true)
{
System.out.print("Yes");
}
// Else print "No"
else
{
System.out.print("No");
}
}
// Driver Code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 4, 1, 3, 2, 5 };
// Starting index
int S = 1;
int N = arr.length;
// Function call
solve(arr, N, S);
}
}
// This code is contributed by gauravrajput1
Python3
# Python3 program for the above approach
from queue import Queue
# Function to check if we can reach to
# the end of the arr[] with possible moves
def solve(arr, n, start):
# Queue to perform BFS
q = Queue()
# Initially all nodes(index)
# are not visited.
visited = [False] * n
# Initially the end of
# the array is not reached
reached = False
# Push start index in queue
q.put(start);
# Until queue becomes empty
while (not q.empty()):
# Get the top element
temp = q.get()
# If the index is already
# visited. No need to
# traverse it again.
if (visited[temp] == True):
continue
# Mark temp as visited, if not
visited[temp] = True
if (temp == n - 1):
# If reached at the end
# of the array then break
reached = True
break
# If temp + arr[temp] and
# temp - arr[temp] are in
# the index of array
if (temp + arr[temp] < n):
q.put(temp + arr[temp])
if (temp - arr[temp] >= 0):
q.put(temp - arr[temp])
# If reaches the end of the array,
# Print "Yes"
if (reached == True):
print("Yes")
# Else print "No"
else:
print("No")
# Driver code
if __name__ == '__main__':
# Given array arr[]
arr = [ 4, 1, 3, 2, 5 ]
# starting index
S = 1
N = len(arr)
# Function call
solve(arr, N, S)
# This code is contributed by himanshu77
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to check if we can reach to
// the end of the []arr with possible moves
static void solve(int []arr, int n,
int start)
{
// Queue to perform BFS
Queue<int> q = new Queue<int>();
// Initially all nodes(index)
// are not visited.
bool []visited = new bool[n];
// Initially the end of
// the array is not reached
bool reached = false;
// Push start index in queue
q.Enqueue(start);
// Until queue becomes empty
while (q.Count != 0)
{
// Get the top element
int temp = q.Peek();
// Delete popped element
q.Dequeue();
// If the index is already
// visited. No need to
// traverse it again.
if (visited[temp] == true)
continue;
// Mark temp as visited
// if not
visited[temp] = true;
if (temp == n - 1)
{
// If reached at the end
// of the array then break
reached = true;
break;
}
// If temp + arr[temp] and
// temp - arr[temp] are in
// the index of array
if (temp + arr[temp] < n)
{
q.Enqueue(temp + arr[temp]);
}
if (temp - arr[temp] >= 0)
{
q.Enqueue(temp - arr[temp]);
}
}
// If reaches the end of the array,
// Print "Yes"
if (reached == true)
{
Console.Write("Yes");
}
// Else print "No"
else
{
Console.Write("No");
}
}
// Driver Code
public static void Main(String[] args)
{
// Given array []arr
int []arr = { 4, 1, 3, 2, 5 };
// Starting index
int S = 1;
int N = arr.Length;
// Function call
solve(arr, N, S);
}
}
// This code is contributed by gauravrajput1
JavaScript
<script>
// Javascript program for the above approach
// Function to check if we can reach to
// the end of the arr[] with possible moves
function solve(arr, n, start)
{
// Queue to perform BFS
let q = [];
// Initially all nodes(index)
// are not visited.
let visited = new Array(n);
visited.fill(false);
// Initially the end of
// the array is not reached
let reached = false;
// Push start index in queue
q.push(start);
// Until queue becomes empty
while (q.length > 0)
{
// Get the top element
let temp = q[0];
// Delete popped element
q.shift();
// If the index is already
// visited. No need to
// traverse it again.
if (visited[temp] == true)
continue;
// Mark temp as visited
// if not
visited[temp] = true;
if (temp == n - 1)
{
// If reached at the end
// of the array then break
reached = true;
break;
}
// If temp + arr[temp] and
// temp - arr[temp] are in
// the index of array
if (temp + arr[temp] < n)
{
q.push(temp + arr[temp]);
}
if (temp - arr[temp] >= 0)
{
q.push(temp - arr[temp]);
}
}
// If reaches the end of the array,
// Print "Yes"
if (reached == true)
{
document.write("Yes");
}
// Else print "No"
else
{
document.write("No");
}
}
// Driver code
// Given array arr[]
let arr = [ 4, 1, 3, 2, 5 ];
// Starting index
let S = 1;
let N = arr.length;
// Function Call
solve(arr, N, S);
// This code is contributed by divyeshrabadiya07
</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.
C++
#include <iostream>
#include <vector>
using namespace std;
bool canReachEnd(vector<int>& arr, int pos) {
// Base case: If the current position is the last index of the array, then we can reach the end.
if (pos == arr.size() - 1) {
return true;
}
// Recursive case: Try all possible jumps from the current position.
int maxJump = min(pos + arr[pos], static_cast<int>(arr.size() - 1));
for (int nextPos = pos + 1; nextPos <= maxJump; nextPos++) {
if (canReachEnd(arr, nextPos)) {
return true;
}
}
// If we can't reach the end from any of the possible jumps, return false.
return false;
}
int main() {
vector<int> arr = {4, 1, 3, 2, 5};
int startPos = 1;
// Example usage
if (canReachEnd(arr, startPos)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
Java
import java.io.*;
public class GFG
{
public static boolean canReachEnd(int[] arr, int pos) {
// Base case: If the current position is the last index of the array then we can reach the end.
if (pos == arr.length - 1) {
return true;
}
// Recursive case: Try all possible jumps from the current position.
int maxJump = Math.min(pos + arr[pos], arr.length - 1);
for (int nextPos = pos + 1; nextPos <= maxJump; nextPos++) {
if (canReachEnd(arr, nextPos)) {
return true;
}
}
// If we can't reach the end from any of the possible jumps return false.
return false;
}
public static void main(String[] args) {
int[] arr = {4, 1, 3, 2, 5};
int startPos = 1;
// Example usage
if (canReachEnd(arr, startPos)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
Python3
def can_reach_end(arr, pos):
# Base case: If the current position is the last index of the array, then we can reach the end.
if pos == len(arr) - 1:
return True
# Recursive case: Try all possible jumps from the current position.
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
# If we can't reach the end from any of the possible jumps, return False.
return False
# Example usage
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)
{
// Base case: If the current position is the last
// index of the array then we can reach the end.
if (pos == arr.Length - 1)
{
return true;
}
// Recursive case: Try all possible jumps from the current position.
int maxJump = Math.Min(pos + arr[pos], arr.Length - 1);
for (int nextPos = pos + 1; nextPos <= maxJump; nextPos++)
{
if (CanReachEnd(arr, nextPos))
{
return true;
}
}
// If we can't reach the end from any of the possible jumps, return false.
return false;
}
public static void Main(string[] args)
{
int[] arr = { 4, 1, 3, 2, 5 };
int startPos = 1;
// Example usage
if (CanReachEnd(arr, startPos))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
JavaScript
function canReachEnd(arr, pos) {
// Base case: If the current position is the last index of the array then we can reach the end.
if (pos == arr.length - 1) {
return true;
}
// Recursive case: Try all possible jumps from the current position.
let maxJump = Math.min(pos + arr[pos], arr.length - 1);
for (let nextPos = pos + 1; nextPos <= maxJump; nextPos++) {
if (canReachEnd(arr, nextPos)) {
return true;
}
}
// If we can't reach the end from any of the possible jumps return false.
return false;
}
let arr = [4, 1, 3, 2, 5];
let startPos = 1;
// Example usage
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem