Open in App
Not now

# Minimize moves to next greater element to reach end of Array

• Difficulty Level : Basic
• 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 ` `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 > 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 s = ``new` `Stack();`   `    ``// 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 q=``new` `LinkedList();;` `    ``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 q = ``new` `Queue();` `    ``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 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

 `= 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` `?>`

Output

`1`

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Related Articles