Minimize moves to next greater element to reach end of Array
Last Updated :
20 Feb, 2023
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
Minimize subtraction of Array elements to make X at most 0
Given a number X, and an array arr[] of length N containing the N numbers. The task is to find the minimum number of operations required to make X non-positive. In one operation: Select any one number Y from the array and reduce X by Y. Then make Y = Y/2 (take floor value if Y is odd).If it is not p
9 min read
Minimum elements to be removed from the ends to make the array sorted
Given an array arr[] of length N, the task is to remove the minimum number of elements from the ends of the array to make the array non-decreasing. Elements can only be removed from the left or the right end. Examples: Input: arr[] = {1, 2, 4, 1, 5} Output: 2 We can't make the array sorted after one
9 min read
Minimizing Moves to Equalize Array Elements
Given an array arr[] of N integers, For each move, you can select any m (1 <= m <= n) elements from the array and transfer one integer unit from each selected element to one of its adjacent elements at the same time, the task is to find the minimum number of moves needed to make all the intege
7 min read
Minimize cost required to make all array elements greater than or equal to zero
Given an array arr[] consisting of N integers and an integer X, the task is to find the minimum cost required to make all array elements greater than or equal to 0 by performing the following operations any number of times: Increase any array element by 1. Cost = 1.Increase all array elements by 1.
7 min read
Smallest greater elements in whole array
An array is given of n length, and we need to calculate the next greater element for each element in the given array. If the next greater element is not available in the given array then we need to fill '_' at that index place. Examples : Input : 6 3 9 8 10 2 1 15 7 Output : 7 6 10 9 15 3 2 _ 8 Here
11 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
Find the Kth smallest element in the sorted generated array
Given an array arr[] of N elements and an integer K, the task is to generate an B[] with the following rules: Copy elements arr[1...N], N times to array B[].Copy elements arr[1...N/2], 2*N times to array B[].Copy elements arr[1...N/4], 3*N times to array B[].Similarly, until only no element is left
8 min read
Find the next greater element in a Circular Array | Set 2
Given a circular array arr[] consisting of N integers, the task is to print the Next Greater Element for every element of the circular array. Elements for which no greater element exist, print â-1â. Examples: Input: arr[] = {5, 6, 7}Output: 6 7 -1Explanation: The next greater element for every array
7 min read
Minimum number of moves to make all elements equal
Given an array containing N elements and an integer K. It is allowed to perform the following operation any number of times on the given array: Insert the K-th element at the end of the array and delete the first element of the array. The task is to find the minimum number of moves needed to make al
7 min read
Minimum Element for Non-Positive Array in Limited Moves
Given the array arr[] and another integer max_moves, Find the minimum possible integer x that must be chosen such that all the elements of the array can be made non-positive in most max_moves operations. In each operation, decrease any element of the array by x. Examples: Input: n = 3, arr = [1, 2,
14 min read