Minimize moves to next greater element to reach end of Array
Last Updated :
23 Jul, 2025
Given an array nums[] of size N and a starting index K. In one move from index i we can move to any other index j such that there exists no element in between the indices that is greater than nums[i] and nums[j] > nums[i]. Find the minimum number of moves to reach the last index. Print -1 if it is not possible.
Examples:
Input: N = 4, K = 0, nums[] = {3, 4, 6, 9}
Output: 3
Explanation: We are initially at index 0. In the first step we can move from index 0 to index 1 because 4 > 3 and there exists no k between 0 and 1 such that nums[k] > nums[0]. Similarly in the second step we can go from index 1 to 2 and in the third index we can go from 2 to 3. Hence minimum moves required is 3.
Input: N = 3, K = 0, nums[] = {0, -1, 2}
Output: 1
Explanation: We are initially at index 0. In the first step we can go from index 0 to index 2 because there is no element between 0 and 2 which is greater than nums[0] (i.e 0). Hence minimum number of steps required is 1.
Approach: The problem can be solved based on the following observation:
From the problem statement, it can be visualized that we need to move from the current element to the next greater element on its right or the next greater element on its left. Then we can apply breadth-first search to find the minimum number of moves required to reach the last index to the end of the array.
Follow the given steps to solve this problem:
- Create two arrays ngel[] and nger[] of size N.
- ngel[i] stores the index of the next greater element on the left for the ith element. Similarly nger[i] stores the index of the next greater element on the right for the ith element.
- Fill arrays ngel[] and nger[] one by one using a stack as discussed in this article.
- Create a queue that stores pairs. The first element in the pair is the index and the second element is the minimum moves required to reach that index starting from K.
- We also take a visited[] array of size N to keep track of the visited indices.
- Initially push the initial index K and 0 into the queue and mark the initial index visited.
- Perform BFS until the queue is not empty.
- Pop the front value from the queue.
- Then store the index and the minimum moves required in two variables (say currentIndex and minMoves).
- If currentIndex is equal to the end of the array return minMoves.
- Otherwise, find the next two locations that we can move using the ngel[] and nger[] values for currentIndex.
- If the ngel[currentIndex] and nger[currentIndex] are valid and not already visited, mark them visited and store them in the queue where the number of moves will be minMoves + 1.
- After iteration, if the last index is not visited, return -1.
Below is the implementation of the above approach:
C++
// C++ code to implement the approach.
#include <bits/stdc++.h>
using namespace std;
// Function to find minimum moves required
// to reach from the initial position to
// the end of the array.
int getMinMoves(int N, int K, vector<int>& nums)
{
// nger stores next greater
// element on right
vector<int> nger(N);
stack<int> s;
// Loop to fill the nger vector
for (int i = N - 1; i >= 0; i--) {
while (!s.empty() and nums[s.top()] <= nums[i]) {
s.pop();
}
if (s.empty()) {
nger[i] = -1;
}
else {
nger[i] = s.top();
}
s.push(i);
}
while (!s.empty()) {
s.pop();
}
// ngel stores next greater
// element on left
vector<int> ngel(N);
// Loop to fill the ngel vector
for (int i = 0; i < N; i++) {
while (!s.empty() and nums[s.top()] <= nums[i]) {
s.pop();
}
if (s.empty()) {
ngel[i] = -1;
}
else {
nger[i] = s.top();
}
s.push(i);
}
// We take a queue of pair to perform
// bfs the first element of the pair
// is the index and the second element
// is the minimum moves from initial
// index to reach that index
queue<pair<int, int> > q;
q.push({ K, 0 });
vector<bool> visited(N, false);
visited[K] = true;
// Perform BFS
while (!q.empty()) {
pair<int, int> par = q.front();
q.pop();
// If the last index is foudn
// return the minimum moves
int currentIndex = par.first;
int minimumMoves = par.second;
if (currentIndex == N - 1) {
return minimumMoves;
}
int child1 = ngel[currentIndex];
int child2 = nger[currentIndex];
if (child1 != -1 and !visited[child1]) {
q.push({ child1, minimumMoves + 1 });
visited[child1] = true;
}
if (child2 != -1 and !visited[child2]) {
q.push({ child2, minimumMoves + 1 });
visited[child2] = true;
}
}
// The last index cannot be reached
return -1;
}
// Driver code
int main()
{
int N, K = 0;
vector<int> nums{ 0, -1, 2 };
N = nums.size();
// Function Call
int minMoves = getMinMoves(N, K, nums);
cout << minMoves << endl;
return 0;
}
Java
// Java code to implement the approach.
import java.io.*;
import java.util.*;
class Pair {
int first, second;
Pair(int fi, int se)
{
first = fi;
second = se;
}
}
class GFG {
// Function to find minimum moves required
// to reach from the initial position to
// the end of the array.
public static int getMinMoves(int N, int K, int nums[])
{
// nger stores next greater
// element on right
int nger[] = new int[N];
Stack<Integer> s = new Stack<Integer>();
// Loop to fill the nger vector
for (int i = N - 1; i >= 0; i--) {
while (!s.isEmpty()
&& nums[s.peek()] <= nums[i]) {
s.pop();
}
if (s.isEmpty()) {
nger[i] = -1;
}
else {
nger[i] = s.peek();
}
s.push(i);
}
while (!s.isEmpty()) {
s.pop();
}
// ngel stores next greater
// element on left
int ngel[] = new int[N];
// Loop to fill the ngel vector
for (int i = 0; i < N; i++) {
while (!s.isEmpty()
&& nums[s.peek()] <= nums[i]) {
s.pop();
}
if (s.isEmpty()) {
ngel[i] = -1;
}
else {
nger[i] = s.peek();
}
s.push(i);
}
// We take a queue of pair to perform
// bfs the first element of the pair
// is the index and the second element
// is the minimum moves from initial
// index to reach that index
Queue<Pair> q=new LinkedList<Pair>();;
Pair p = new Pair(K, 0);
q.add(p);
int visited[] = new int[N];
visited[K] = 1;
// Perform BFS
while (!q.isEmpty()) {
Pair par = q.peek();
q.remove();
// If the last index is foudn
// return the minimum moves
int currentIndex = par.first;
int minimumMoves = par.second;
if (currentIndex == N - 1) {
return minimumMoves;
}
int child1 = ngel[currentIndex];
int child2 = nger[currentIndex];
if (child1 != -1 && visited[child1] == 0) {
Pair temp
= new Pair(child1, minimumMoves + 1);
q.add(temp);
visited[child1] = 1;
}
if (child2 != -1 && visited[child2] == 0) {
Pair temp
= new Pair(child2, minimumMoves + 1);
q.add(temp);
visited[child2] = 1;
}
}
// The last index cannot be reached
return -1;
}
// Driver Code
public static void main(String[] args)
{
int N, K = 0;
int nums[] = { 0, -1, 2 };
N = nums.length;
// Function Call
int minMoves = getMinMoves(N, K, nums);
System.out.print(minMoves);
}
}
// This code is contributed by Rohit Pradhan
Python3
# python3 code to implement the approach.
# Function to find minimum moves required
# to reach from the initial position to
# the end of the array.
def getMinMoves(N, K, nums):
# nger stores next greater
# element on right
nger = [0 for _ in range(N)]
s = []
# Loop to fill the nger vector
for i in range(N-1, -1, -1):
while (len(s) != 0 and nums[s[len(s) - 1]] <= nums[i]):
s.pop()
if (len(s) == 0):
nger[i] = -1
else:
nger[i] = s[len(s) - 1]
s.append(i)
while (len(s) != 0):
s.pop()
# ngel stores next greater
# element on left
ngel = [0 for _ in range(N)]
# Loop to fill the ngel vector
for i in range(0, N):
while(len(s) != 0 and nums[s[len(s) - 1]] <= nums[i]):
s.pop()
if (len(s) == 0):
ngel[i] = -1
else:
nger[i] = s[len(s) - 1]
s.append(i)
# We take a queue of pair to perform
# bfs the first element of the pair
# is the index and the second element
# is the minimum moves from initial
# index to reach that index
q = []
q.append([K, 0])
visited = [False for _ in range(N)]
visited[K] = True
# Perform BFS
while (len(q) != 0):
par = q[0]
q.pop(0)
# If the last index is foudn
# return the minimum moves
currentIndex = par[0]
minimumMoves = par[1]
if (currentIndex == N - 1):
return minimumMoves
child1 = ngel[currentIndex]
child2 = nger[currentIndex]
if (child1 != -1 and (not visited[child1])):
q.append([child1, minimumMoves + 1])
visited[child1] = True
if (child2 != -1 and not visited[child2]):
q.append([child2, minimumMoves + 1])
visited[child2] = True
# The last index cannot be reached
return -1
# Driver code
if __name__ == "__main__":
N, K = 0, 0
nums = [0, -1, 2]
N = len(nums)
# Function Call
minMoves = getMinMoves(N, K, nums)
print(minMoves)
# This code is contributed by rakeshsahni
C#
using System;
using System.Collections.Generic;
public class Pair {
public int first, second;
public Pair(int fi, int se)
{
first = fi;
second = se;
}
}
public class GFG {
// Function to find minimum moves required
// to reach from the initial position to
// the end of the array.
public static int getMinMoves(int N, int K, int[] nums)
{
// nger stores next greater
// element on right
List<int> nger = new List<int>();
for (int i = 0; i < N; i++) {
nger.Add(0);
}
Stack<int> s = new Stack<int>();
// Loop to fill the nger vector
for (int i = N - 1; i >= 0; i--) {
while (s.Count != 0
&& nums[(int)s.Peek()] <= nums[i]) {
s.Pop();
}
if (s.Count == 0) {
nger[i] = -1;
}
else {
nger[i] = s.Peek();
}
s.Push(i);
}
while (s.Count != 0) {
s.Pop();
}
// ngel stores next greater
// element on left
List<int> ngel = new List<int>();
for (int i = 0; i < N; i++) {
ngel.Add(0);
}
// Loop to fill the ngel vector
for (int i = 0; i < N; i++) {
while (s.Count != 0
&& nums[(int)s.Peek()] <= nums[i]) {
s.Pop();
}
if (s.Count == 0) {
ngel[i] = -1;
}
else {
nger[i] = s.Peek();
}
s.Push(i);
}
// We take a queue of pair to perform
// bfs the first element of the pair
// is the index and the second element
// is the minimum moves from initial
// index to reach that index
Queue<Pair> q = new Queue<Pair>();
Pair p = new Pair(K, 0);
q.Enqueue(p);
List<bool> visited = new List<bool>();
for (int i = 0; i < N; i++) {
visited.Add(false);
}
visited[K] = true;
// Perform BFS
while (q.Count != 0) {
Pair par = q.Peek();
q.Dequeue();
// If the last index is foudn
// return the minimum moves
int currentIndex = par.first;
int minimumMoves = par.second;
if (currentIndex == N - 1) {
return minimumMoves;
}
int child1 = ngel[currentIndex];
int child2 = nger[currentIndex];
if (child1 != -1 && visited[child1] == false) {
Pair temp
= new Pair(child1, minimumMoves + 1);
q.Enqueue(temp);
visited[child1] = true;
}
if (child2 != -1 && visited[child2] == false) {
Pair temp
= new Pair(child2, minimumMoves + 1);
q.Enqueue(temp);
visited[child2] = true;
}
}
// The last index cannot be reached
return -1;
}
// Driver Code
static public void Main()
{
// Code
int K = 0;
int[] nums = { 0, -1, 2 };
int N = nums.Length;
// Function Call
int minMoves = getMinMoves(N, K, nums);
Console.Write(minMoves);
}
}
// This code is contributed by akashish__
JavaScript
// Javascript code to implement the approach.
// Function to find minimum moves required
// to reach from the initial position to
// the end of the array.
function getMinMoves(N, K, nums)
{
// nger stores next greater
// element on right
let nger = [];
for (let i = 0; i < N; i++) {
nger.push(0);
}
let s = [];
// Loop to fill the nger vector
for (let i = N - 1; i >= 0; i--) {
while (s.length > 0 && nums[s[s.length - 1]] <= nums[i]) {
s.pop();
}
if (s.length == 0) {
nger[i] = -1;
}
else {
nger[i] = s[s.length - 1];
}
s.push(i);
}
while (s.length > 0) {
s.pop();
}
// ngel stores next greater
// element on left
// vector<int> ngel(N);
let ngel = [];
for (let i = 0; i < N; i++)
ngel.push(0);
// Loop to fill the ngel vector
for (let i = 0; i < N; i++) {
while (s.length > 0 && nums[s[s.length - 1]] <= nums[i]) {
s.pop();
}
if (s.length == 0) {
ngel[i] = -1;
}
else {
nger[i] = s[s.length - 1];
}
s.push(i);
}
// We take a queue of pair to perform
// bfs the first element of the pair
// is the index and the second element
// is the minimum moves from initial
// index to reach that index
let q = [];
q.push({
"first": K,
"second": 0
});
let visited = [];
for (let i = 0; i < N; i++) {
visited.push(false);
}
visited[K] = true;
// Perform BFS
while (q.length > 0) {
let par = q[0];
q.shift();
// If the last index is foudn
// return the minimum moves
let currentIndex = par.first;
let minimumMoves = par.second;
if (currentIndex == N - 1) {
return minimumMoves;
}
let child1 = ngel[currentIndex];
let child2 = nger[currentIndex];
if (child1 != -1 && visited[child1] == false) {
q.push({
"first": child1,
"second": minimumMoves + 1
});
visited[child1] = true;
}
if (child2 != -1 && visited[child2] == false) {
q.push({
"first": child2,
"second": minimumMoves + 1
});
visited[child2] = true;
}
}
// The last index cannot be reached
return -1;
}
// Driver code
let N = 0;
let K = 0;
let nums = [0, -1, 2];
N = nums.length;
// Function Call
let minMoves = getMinMoves(N, K, nums);
console.log(minMoves);
// This code is contributed by akashish__
PHP
<?php
// Function to find minimum moves required
// to reach from the initial position to
// the end of the array.
function getMinMoves($N, $K, $nums)
{
// nger stores next greater
// element on right
$nger = array_fill(0, $N, 0);
$s = array();
// Loop to fill the nger vector
for ($i = $N - 1; $i >= 0; $i--)
{
while (!empty($s) and $nums[$s[count($s) - 1]]
<= $nums[$i])
{
array_pop($s);
}
if (empty($s))
$nger[$i] = -1;
else
$nger[$i] = $s[count($s) - 1];
array_push($s, $i);
}
$s = array();
// ngel stores next greater
// element on left
$ngel = array_fill(0, $N, 0);
// Loop to fill the ngel vector
for ($i = 0; $i < $N; $i++)
{
while (!empty($s) and $nums[$s[count($s) - 1]]
<= $nums[$i])
{
array_pop($s);
}
if (empty($s))
$ngel[$i] = -1;
else
$ngel[$i] = $s[count($s) - 1];
array_push($s, $i);
}
// We take a queue of pair to perform
// bfs the first element of the pair
// is the index and the second element
// is the minimum moves from initial
// index to reach that index
$q = array(array($K, 0));
$visited = array_fill(0, $N, false);
$visited[$K] = true;
// Perform BFS
while (!empty($q))
{
$par = array_shift($q);
// If the last index is foudn
// return the minimum moves
$currentIndex = $par[0];
$minimumMoves = $par[1];
if ($currentIndex == $N - 1)
return $minimumMoves;
$child1 = $ngel[$currentIndex];
$child2 = $nger[$currentIndex];
if ($child1 != -1 and !$visited[$child1])
{
array_push($q, array($child1,
$minimumMoves + 1));
$visited[$child1] = true;
}
if ($child2 != -1 and !$visited[$child2])
{
array_push($q, array($child2,
$minimumMoves + 1));
$visited[$child2] = true;
}
}
// The last index cannot be reached
return -1;
}
// Driver code
$N = 3;
$K = 0;
$nums = array(0, -1, 2);
// Function Call
$minMoves = getMinMoves($N, $K, $nums);
echo $minMoves;
// This code is contributed by Kanishka Gupta
?>
Time Complexity: O(N)
Auxiliary Space: O(N)
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