Minimum steps to reach end of array under constraints
Last Updated :
18 Sep, 2023
Given an array containing one digit numbers only, assuming we are standing at first index, we need to reach to end of array using minimum number of steps where in one step, we can jump to neighbor indices or can jump to a position with same value.
In other words, if we are at index i, then in one step you can reach to, arr[i-1] or arr[i+1] or arr[K] such that arr[K] = arr[i] (value of arr[K] is same as arr[i])
Examples:
Input : arr[] = {5, 4, 2, 5, 0}
Output : 2
Explanation : Total 2 step required.
We start from 5(0), in first step jump to next 5
and in second step we move to value 0 (End of arr[]).
Input : arr[] = [0, 1, 2, 3, 4, 5, 6, 7, 5, 4,
3, 6, 0, 1, 2, 3, 4, 5, 7]
Output : 5
Explanation : Total 5 step required.
0(0) -> 0(12) -> 6(11) -> 6(6) -> 7(7) ->
(18)
(inside parenthesis indices are shown)
This problem can be solved using BFS. We can consider the given array as unweighted graph where every vertex has two edges to next and previous array elements and more edges to array elements with same values. Now for fast processing of third type of edges, we keep 10 vectors which store all indices where digits 0 to 9 are present. In above example, vector corresponding to 0 will store [0, 12], 2 indices where 0 has occurred in given array.
Another Boolean array is used, so that we don’t visit same index more than once. As we are using BFS and BFS proceeds level by level, optimal minimum steps are guaranteed.
Implementation:
C++
// C++ program to find minimum jumps to reach end
// of array
#include <bits/stdc++.h>
using namespace std;
// Method returns minimum step to reach end of array
int getMinStepToReachEnd(int arr[], int N)
{
// visit boolean array checks whether current index
// is previously visited
bool visit[N];
// distance array stores distance of current
// index from starting index
int distance[N];
// digit vector stores indices where a
// particular number resides
vector<int> digit[10];
// In starting all index are unvisited
memset(visit, false, sizeof(visit));
// storing indices of each number in digit vector
for (int i = 1; i < N; i++)
digit[arr[i]].push_back(i);
// for starting index distance will be zero
distance[0] = 0;
visit[0] = true;
// Creating a queue and inserting index 0.
queue<int> q;
q.push(0);
// loop until queue in not empty
while(!q.empty())
{
// Get an item from queue, q.
int idx = q.front(); q.pop();
// If we reached to last index break from loop
if (idx == N-1)
break;
// Find value of dequeued index
int d = arr[idx];
// looping for all indices with value as d.
for (int i = 0; i<digit[d].size(); i++)
{
int nextidx = digit[d][i];
if (!visit[nextidx])
{
visit[nextidx] = true;
q.push(nextidx);
// update the distance of this nextidx
distance[nextidx] = distance[idx] + 1;
}
}
// clear all indices for digit d, because all
// of them are processed
digit[d].clear();
// checking condition for previous index
if (idx-1 >= 0 && !visit[idx - 1])
{
visit[idx - 1] = true;
q.push(idx - 1);
distance[idx - 1] = distance[idx] + 1;
}
// checking condition for next index
if (idx + 1 < N && !visit[idx + 1])
{
visit[idx + 1] = true;
q.push(idx + 1);
distance[idx + 1] = distance[idx] + 1;
}
}
// N-1th position has the final result
return distance[N - 1];
}
// driver code to test above methods
int main()
{
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 5,
4, 3, 6, 0, 1, 2, 3, 4, 5, 7};
int N = sizeof(arr) / sizeof(int);
cout << getMinStepToReachEnd(arr, N);
return 0;
}
Java
// Java program to find minimum jumps
// to reach end of array
import java.util.*;
class GFG
{
// Method returns minimum step
// to reach end of array
static int getMinStepToReachEnd(int arr[],
int N)
{
// visit boolean array checks whether
// current index is previously visited
boolean []visit = new boolean[N];
// distance array stores distance of
// current index from starting index
int []distance = new int[N];
// digit vector stores indices where a
// particular number resides
Vector<Integer> []digit = new Vector[10];
for(int i = 0; i < 10; i++)
digit[i] = new Vector<>();
// In starting all index are unvisited
for(int i = 0; i < N; i++)
visit[i] = false;
// storing indices of each number
// in digit vector
for (int i = 1; i < N; i++)
digit[arr[i]].add(i);
// for starting index distance will be zero
distance[0] = 0;
visit[0] = true;
// Creating a queue and inserting index 0.
Queue<Integer> q = new LinkedList<>();
q.add(0);
// loop until queue in not empty
while(!q.isEmpty())
{
// Get an item from queue, q.
int idx = q.peek();
q.remove();
// If we reached to last
// index break from loop
if (idx == N - 1)
break;
// Find value of dequeued index
int d = arr[idx];
// looping for all indices with value as d.
for (int i = 0; i < digit[d].size(); i++)
{
int nextidx = digit[d].get(i);
if (!visit[nextidx])
{
visit[nextidx] = true;
q.add(nextidx);
// update the distance of this nextidx
distance[nextidx] = distance[idx] + 1;
}
}
// clear all indices for digit d,
// because all of them are processed
digit[d].clear();
// checking condition for previous index
if (idx - 1 >= 0 && !visit[idx - 1])
{
visit[idx - 1] = true;
q.add(idx - 1);
distance[idx - 1] = distance[idx] + 1;
}
// checking condition for next index
if (idx + 1 < N && !visit[idx + 1])
{
visit[idx + 1] = true;
q.add(idx + 1);
distance[idx + 1] = distance[idx] + 1;
}
}
// N-1th position has the final result
return distance[N - 1];
}
// Driver Code
public static void main(String []args)
{
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 5,
4, 3, 6, 0, 1, 2, 3, 4, 5, 7};
int N = arr.length;
System.out.println(getMinStepToReachEnd(arr, N));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python 3 program to find minimum jumps to reach end# of array
# Method returns minimum step to reach end of array
def getMinStepToReachEnd(arr,N):
# visit boolean array checks whether current index
# is previously visited
visit = [False for i in range(N)]
# distance array stores distance of current
# index from starting index
distance = [0 for i in range(N)]
# digit vector stores indices where a
# particular number resides
digit = [[0 for i in range(N)] for j in range(10)]
# storing indices of each number in digit vector
for i in range(1,N):
digit[arr[i]].append(i)
# for starting index distance will be zero
distance[0] = 0
visit[0] = True
# Creating a queue and inserting index 0.
q = []
q.append(0)
# loop until queue in not empty
while(len(q)> 0):
# Get an item from queue, q.
idx = q[0]
q.remove(q[0])
# If we reached to last index break from loop
if (idx == N-1):
break
# Find value of dequeued index
d = arr[idx]
# looping for all indices with value as d.
for i in range(len(digit[d])):
nextidx = digit[d][i]
if (visit[nextidx] == False):
visit[nextidx] = True
q.append(nextidx)
# update the distance of this nextidx
distance[nextidx] = distance[idx] + 1
# clear all indices for digit d, because all
# of them are processed
# checking condition for previous index
if (idx-1 >= 0 and visit[idx - 1] == False):
visit[idx - 1] = True
q.append(idx - 1)
distance[idx - 1] = distance[idx] + 1
# checking condition for next index
if (idx + 1 < N and visit[idx + 1] == False):
visit[idx + 1] = True
q.append(idx + 1)
distance[idx + 1] = distance[idx] + 1
# N-1th position has the final result
return distance[N - 1]
# driver code to test above methods
if __name__ == '__main__':
arr = [0, 1, 2, 3, 4, 5, 6, 7, 5, 4, 3, 6, 0, 1, 2, 3, 4, 5, 7]
N = len(arr)
print(getMinStepToReachEnd(arr, N))
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to find minimum jumps
// to reach end of array
using System;
using System.Collections.Generic;
class GFG
{
// Method returns minimum step
// to reach end of array
static int getMinStepToReachEnd(int []arr,
int N)
{
// visit boolean array checks whether
// current index is previously visited
bool []visit = new bool[N];
// distance array stores distance of
// current index from starting index
int []distance = new int[N];
// digit vector stores indices where a
// particular number resides
List<int> []digit = new List<int>[10];
for(int i = 0; i < 10; i++)
digit[i] = new List<int>();
// In starting all index are unvisited
for(int i = 0; i < N; i++)
visit[i] = false;
// storing indices of each number
// in digit vector
for (int i = 1; i < N; i++)
digit[arr[i]].Add(i);
// for starting index distance will be zero
distance[0] = 0;
visit[0] = true;
// Creating a queue and inserting index 0.
Queue<int> q = new Queue<int>();
q.Enqueue(0);
// loop until queue in not empty
while(q.Count != 0)
{
// Get an item from queue, q.
int idx = q.Peek();
q.Dequeue();
// If we reached to last
// index break from loop
if (idx == N - 1)
break;
// Find value of dequeued index
int d = arr[idx];
// looping for all indices with value as d.
for (int i = 0; i < digit[d].Count; i++)
{
int nextidx = digit[d][i];
if (!visit[nextidx])
{
visit[nextidx] = true;
q.Enqueue(nextidx);
// update the distance of this nextidx
distance[nextidx] = distance[idx] + 1;
}
}
// clear all indices for digit d,
// because all of them are processed
digit[d].Clear();
// checking condition for previous index
if (idx - 1 >= 0 && !visit[idx - 1])
{
visit[idx - 1] = true;
q.Enqueue(idx - 1);
distance[idx - 1] = distance[idx] + 1;
}
// checking condition for next index
if (idx + 1 < N && !visit[idx + 1])
{
visit[idx + 1] = true;
q.Enqueue(idx + 1);
distance[idx + 1] = distance[idx] + 1;
}
}
// N-1th position has the final result
return distance[N - 1];
}
// Driver Code
public static void Main(String []args)
{
int []arr = {0, 1, 2, 3, 4, 5, 6, 7, 5,
4, 3, 6, 0, 1, 2, 3, 4, 5, 7};
int N = arr.Length;
Console.WriteLine(getMinStepToReachEnd(arr, N));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript program to find minimum jumps
// to reach end of array
// Method returns minimum step
// to reach end of array
function getMinStepToReachEnd(arr,N)
{
// visit boolean array checks whether
// current index is previously visited
let visit = new Array(N);
// distance array stores distance of
// current index from starting index
let distance = new Array(N);
// digit vector stores indices where a
// particular number resides
let digit = new Array(10);
for(let i = 0; i < 10; i++)
digit[i] = [];
// In starting all index are unvisited
for(let i = 0; i < N; i++)
visit[i] = false;
// storing indices of each number
// in digit vector
for (let i = 1; i < N; i++)
digit[arr[i]].push(i);
// for starting index distance will be zero
distance[0] = 0;
visit[0] = true;
// Creating a queue and inserting index 0.
let q = [];
q.push(0);
// loop until queue in not empty
while(q.length!=0)
{
// Get an item from queue, q.
let idx = q.shift();
// If we reached to last
// index break from loop
if (idx == N - 1)
break;
// Find value of dequeued index
let d = arr[idx];
// looping for all indices with value as d.
for (let i = 0; i < digit[d].length; i++)
{
let nextidx = digit[d][i];
if (!visit[nextidx])
{
visit[nextidx] = true;
q.push(nextidx);
// update the distance of this nextidx
distance[nextidx] = distance[idx] + 1;
}
}
// clear all indices for digit d,
// because all of them are processed
digit[d]=[];
// checking condition for previous index
if (idx - 1 >= 0 && !visit[idx - 1])
{
visit[idx - 1] = true;
q.push(idx - 1);
distance[idx - 1] = distance[idx] + 1;
}
// checking condition for next index
if (idx + 1 < N && !visit[idx + 1])
{
visit[idx + 1] = true;
q.push(idx + 1);
distance[idx + 1] = distance[idx] + 1;
}
}
// N-1th position has the final result
return distance[N - 1];
}
// Driver Code
let arr=[0, 1, 2, 3, 4, 5, 6, 7, 5,
4, 3, 6, 0, 1, 2, 3, 4, 5, 7];
let N = arr.length;
document.write(getMinStepToReachEnd(arr, N));
// This code is contributed by rag2127
</script>
Time Complexity: O(N), where N is the number of elements in the array.
Space Complexity: O(N), where N is the number of elements in the array. We are using a distance and visit array of size N and a queue of size N to store the indices of the array.
Similar Reads
Minimum jumps to reach end of the array with given conditions
Given an array A[], the task is to print the minimum number of jumps needed to reach the last element of A[] starting from the first element. If it is impossible to reach the last element print -1. A jump can be made from index i to j if all the below conditions are met: i < jA[i] >= A[j]There
6 min read
Minimum steps required to reach the end of Array with a given capacity
Given an array arr[] of size n. You will have to traverse the array from left to right deducting each element of the array from the initial capacity, such that your initial capacity should never go below 0. In case, the current capacity is less than the current element, we can traverse back to the s
15 min read
Minimum steps to reach a given index in the Array based on given conditions
Given an array arr[ ] of size N consisting of integers -1, 0, 1 only and an array q[ ] consisting of queries. In the array arr[ ], -1 signifies that any index to the left of it is reachable and 1 signifies that any index to the right of it is reachable from that index. The index in a particular quer
10 min read
Minimum jumps to same value or adjacent to reach end of Array
Given an array arr[] of size N, the task is to find the minimum number of jumps to reach the last index of the array starting from index 0. In one jump you can move from current index i to index j, if arr[i] = arr[j] and i != j or you can jump to (i + 1) or (i â 1).Note: You can not jump outside of
13 min read
Minimum cost to equal all elements of array using two operation
Given an array arr[] of n positive integers. There are two operations allowed: Operation 1 : Pick any two indexes, increase value at one index by 1 and decrease value at another index by 1. It will cost a. Operation 2 : Pick any index and increase its value by 1. It will cost b. The task is to find
8 min read
Minimum cost to reach the end of the array with maximum jumps of length K
Given an array arr[] of size N and an integer K, one can move from an index i to any other index j such that j ? i+k. The cost of being at any index 'i', is arr[i]. The task is to find the minimum cost to reach the end of the array starting from index 0. Examples: Input : arr[] = {2, 4, 1, 6, 3}, K
10 min read
Maximize count of elements reaching the end of an Array
Given an array arr[] consisting of N integers, where each element denotes the maximum number of elements that can be placed on that index and an integer X, which denotes the maximum indices that can be jumped from an index, the task is to find the number of elements that can reach the end of the arr
15 min read
Minimum Increments to reach the given MEX
Given an array arr[] of size N. In one operation, choose any element of the array and increase its value by 1. The task is to determine the minimum operations to make the MEX of the array equal to i, for each i from 0 to N. The MEX of the array is equal to the minimum non-negative integer that is no
9 min read
Forming smallest array with given constraints
Given three integers x, y and z (can be negative). The task is to find the length of the smallest array that can be made such that absolute difference between adjacent elements is less than or equal to 1, the first element of the array is x, having one integer y and last element z. Examples: Input :
4 min read
Find the minimum number of moves to reach end of the array
Given an array arr[] of size N where every element is from the range [0, 9]. The task is to reach the last index of the array starting from the first index. From ith index we can move to (i - 1)th, (i + 1)th or to any jth index where j ? i and arr[j] = arr[i]. Examples: Input: arr[] = {1, 2, 3, 4, 1
11 min read