Find the next greater element in a Circular Array
Given a circular array arr[] of N integers such that the last element of the given array is adjacent to the first element of the array, the task is to print the Next Greater Element in this circular array. Elements for which no greater element exist, consider the next greater element as “-1”.
Examples:
Input: arr[] = {5, 6, 7}
Output: {6, 7, -1}
Explanation:
Next Greater Element for 5 is 6, for 6 is 7, and for 7 is -1 as we don’t have any element greater than itself so its -1.Input: arr[] = {4, -2, 5, 8}
Output: {5, 5, 8, -1}
Explanation:
Next Greater Element for 4 is 5, for -2 its 5, for 5 is 8, and for 8 is -1 as we don’t have any element greater than itself so its -1, and for 3 its 4.
Approach: This problem can be solved using Greedy Approach. Below are the steps:
- For the property of the circular array to be valid append the given array elements to the same array once again.
For Example:
Let arr[] = {1, 4, 3}
After appending the same set of elements arr[] becomes
arr[] = {1, 4, 3, 1, 4, 3}
- Find the next greater element till N elements in the above array formed.
- If any greater element is found then print that element, else print “-1”.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find the NGE void printNGE( int A[], int n) { // Formation of circular array int arr[2 * n]; // Append the given array element twice for ( int i = 0; i < 2 * n; i++) arr[i] = A[i % n]; int next, i, j; // Iterate for all the elements of the array for (i = 0; i < n; i++) { // Initialise NGE as -1 next = -1; for (j = i + 1; j < 2 * n; j++) { // Checking for next greater element if (arr[i] < arr[j]) { next = arr[j]; break ; } } // Print the updated NGE cout << next << ", " ; } } // Driver Code int main() { // Given array arr[] int arr[] = { 1, 2, 1 }; int N = sizeof (arr) / sizeof (arr[0]); // Function call printNGE(arr, N); return 0; } // This code is contributed by Aditya Kumar (adityakumar129) |
C
// C program for the above approach #include <stdio.h> // Function to find the NGE void printNGE( int A[], int n) { // Formation of circular array int arr[2 * n]; // Append the given array element twice for ( int i = 0; i < 2 * n; i++) arr[i] = A[i % n]; int next, i, j; // Iterate for all the elements of the array for (i = 0; i < n; i++) { // Initialise NGE as -1 next = -1; for (j = i + 1; j < 2 * n; j++) { // Checking for next greater element if (arr[i] < arr[j]) { next = arr[j]; break ; } } // Print the updated NGE printf ( "%d, " ,next); } } // Driver Code int main() { // Given array arr[] int arr[] = { 1, 2, 1 }; int N = sizeof (arr) / sizeof (arr[0]); // Function call printNGE(arr, N); return 0; } // This code is contributed by Aditya Kumar (adityakumar129) |
Java
// Java program for the above approach import java.util.*; class GFG { // Function to find the NGE static void printNGE( int [] A, int n) { // Formation of circular array int [] arr = new int [ 2 * n]; // Append the given array element twice for ( int i = 0 ; i < 2 * n; i++) arr[i] = A[i % n]; int next; // Iterate for all the elements of the array for ( int i = 0 ; i < n; i++) { // Initialise NGE as -1 next = - 1 ; for ( int j = i + 1 ; j < 2 * n; j++) { // Checking for next greater element if (arr[i] < arr[j]) { next = arr[j]; break ; } } // Print the updated NGE System.out.print(next + ", " ); } } // Driver Code public static void main(String args[]) { // Given array arr[] int [] arr = { 1 , 2 , 1 }; int N = arr.length; // Function call printNGE(arr, N); } } // This code is contributed by Aditya Kumar (adityakumar129) |
Python3
# Python3 program for the above approach # Function to find the NGE def printNGE(A, n): # Formation of circular array arr = [ 0 ] * ( 2 * n) # Append the given array # element twice for i in range ( 2 * n): arr[i] = A[i % n] # Iterate for all the # elements of the array for i in range (n): # Initialise NGE as -1 next = - 1 for j in range (i + 1 , 2 * n): # Checking for next # greater element if (arr[i] < arr[j]): next = arr[j] break # Print the updated NGE print ( next , end = ", " ) # Driver code if __name__ = = '__main__' : # Given array arr[] arr = [ 1 , 2 , 1 ] N = len (arr) # Function call printNGE(arr, N) # This code is contributed by Shivam Singh |
C#
// C# program for the above approach using System; class GFG{ // Function to find the NGE static void printNGE( int []A, int n) { // Formation of circular array int []arr = new int [2 * n]; // Append the given array element twice for ( int i = 0; i < 2 * n; i++) arr[i] = A[i % n]; int next; // Iterate for all the // elements of the array for ( int i = 0; i < n; i++) { // Initialise NGE as -1 next = -1; for ( int j = i + 1; j < 2 * n; j++) { // Checking for next // greater element if (arr[i] < arr[j]) { next = arr[j]; break ; } } // Print the updated NGE Console.Write(next + ", " ); } } // Driver Code public static void Main() { // Given array arr[] int []arr = { 1, 2, 1 }; int N = arr.Length; // Function call printNGE(arr, N); } } // This code is contributed by Code_Mech |
Javascript
<script> // JavaScript program for the above approach // Function to find the NGE function printNGE(A, n) { // Formation of circular array let arr = Array.from({length: 2 * n}, (_, i) => 0); // Append the given array element twice for (let i = 0; i < 2 * n; i++) arr[i] = A[i % n]; let next; // Iterate for all the // elements of the array for (let i = 0; i < n; i++) { // Initialise NGE as -1 next = -1; for (let j = i + 1; j < 2 * n; j++) { // Checking for next // greater element if (arr[i] < arr[j]) { next = arr[j]; break ; } } // Print the updated NGE document.write(next + ", " ); } } // Driver Code // Given array arr[] let arr = [ 1, 2, 1 ]; let N = arr.length; // Function call printNGE(arr, N); </script> |
2, -1, 2,
This approach takes of O(n2) time but takes extra space of order O(n)
A space-efficient solution is to deal with circular arrays using the same array. If a careful observation is run through the array, then after the n-th index, the next index always starts from 0 so using the mod operator, we can easily access the elements of the circular list, if we use (i)%n and run the loop from i-th index to n+i-th index, and apply mod we can do the traversal in a circular array within the given array without using any extra space.
Below is the implementation of the above approach:
C++
// C++ program to demonstrate the use of circular // array without using extra memory space #include <bits/stdc++.h> using namespace std; // Function to find the Next Greater Element(NGE) void printNGE( int A[], int n) { int k; for ( int i = 0; i < n; i++) { // Initialise k as -1 which is printed // when no NGE found k = -1; for ( int j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { cout << " " << A[j % n]; k = 1; break ; } } // Gets executed when no NGE found if (k == -1) cout << "-1 " ; } } // Driver Code int main() { // Given array arr[] int arr[] = { 8, 6, 7 }; int N = sizeof (arr) / sizeof (arr[0]); // Function call printNGE(arr, N); return 0; } // This code is contributed by Aditya Kumar (adityakumar129) |
C
// C program to demonstrate the use of circular // array without using extra memory space #include <stdio.h> // Function to find the Next Greater Element(NGE) void printNGE( int A[], int n) { int k; for ( int i = 0; i < n; i++) { // Initialise k as -1 which is printed when no NGE // found k = -1; // for ( int j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { printf ( "%d " , A[j % n]); k = 1; break ; } } if (k == -1) // Gets executed when no NGE found printf ( "-1 " ); } } // Driver Code int main() { // Given array arr[] int arr[] = { 8, 6, 7 }; int N = sizeof (arr) / sizeof (arr[0]); // Function call printNGE(arr, N); return 0; } |
Java
// Java program to demonstrate the use of circular array // without using extra memory space import java.io.*; class GFG { // Function to find the Next // Greater Element(NGE) static void printNGE( int A[], int n) { int k; for ( int i = 0 ; i < n; i++) { // Initialise k as -1 which is printed when no // NGE found k = - 1 ; for ( int j = i + 1 ; j < n + i; j++) { if (A[i] < A[j % n]) { System.out.print(A[j % n] + " " ); k = 1 ; break ; } } // Gets executed when no NGE found if (k == - 1 ) System.out.print( "-1 " ); } } // Driver Code public static void main(String[] args) { // Given array arr[] int [] arr = { 8 , 6 , 7 }; int N = arr.length; // Function call printNGE(arr, N); } } // This code is contributed by Aditya Kumar (adityakumar129) |
Python3
# Python3 program to demonstrate the use of circular # array without using extra memory space # Function to find the Next Greater Element(NGE) def printNGE(A, n) : for i in range (n) : # Initialise k as -1 which is printed when no NGE # found k = - 1 for j in range (i + 1 , n + i) : if (A[i] < A[j % n]) : print (A[j % n], end = " " ) k = 1 break if (k = = - 1 ) : # Gets executed when no NGE found print ( "-1 " , end = "") # Given array arr[] arr = [ 8 , 6 , 7 ] N = len (arr) # Function call printNGE(arr, N) # This code is contributed by divyeshrabadia07 |
C#
// C# program to demonstrate the // use of circular array without // using extra memory space using System; class GFG { // Function to find the Next // Greater Element(NGE) static void printNGE( int [] A, int n) { int k; for ( int i = 0; i < n; i++) { // Initialise k as -1 which is // printed when no NGE found k = -1; for ( int j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { Console.Write(A[j % n] + " " ); k = 1; break ; } } // Gets executed when no NGE found if (k == -1) Console.Write( "-1 " ); } } static void Main() { // Given array arr[] int [] arr = { 8, 6, 7 }; int N = arr.Length; // Function call printNGE(arr, N); } } // This code is contributed by divyesh072019 |
Javascript
<script> // JavaScript program to demonstrate the // use of circular array without // using extra memory space // Function to find the Next // Greater Element(NGE) function printNGE(A, n) { let k; for (let i = 0; i < n; i++) { // Initialise k as -1 which is // printed when no NGE found k = -1; for (let j = i + 1; j < n + i; j++) { if (A[i] < A[j % n]) { document.write(A[j % n] + " " ); k = 1; break ; } } // Gets executed when no NGE found if (k == -1) document.write( "-1 " ); } } // Given array arr[] let arr = [ 8, 6, 7 ]; let N = arr.length; // Function call printNGE(arr, N); </script> |
-1 7 8
Time Complexity: O(n2)
Auxiliary Space: O(1)
Method 3rd: The method uses the same concept used in method 2 for circular Array but uses Stack to find out the next greater element in O(n) time complexity where n is the size of the array. For better understanding, you can see the next greater element.
C++
#include <bits/stdc++.h> using namespace std; // Function to find the Next Greater Element(NGE) void printNGE( int a[], int n) { stack< int > s; vector< int > ans(n); for ( int i = 2 * n - 1; i >= 0; i--) { while (!s.empty() && a[i % n] >= s.top()) s.pop(); if (i < n) { if (!s.empty()) ans[i] = s.top(); else ans[i] = -1; } s.push(a[i % n]); } for ( int i = 0; i < n; i++) cout << ans[i] << " " ; } // Driver Code int main() { int arr[] = { 8, 6, 7 }; int N = sizeof (arr) / sizeof (arr[0]); printNGE(arr, N); return 0; } |
Java
/*package whatever //do not write package name here */ import java.io.*; import java.util.*; class GFG { public static void printNGE( int [] arr) { Stack<Integer> stack = new Stack<>(); int n = arr.length; int [] result = new int [n]; for ( int i = 2 *n - 1 ; i >= 0 ; i--) { // Remove all the elements in Stack that are less than arr[i%n] while (!stack.isEmpty() && arr[i % n] >= stack.peek()){ stack.pop(); } if (i < n) { if (!stack.isEmpty()) result[i] = stack.peek(); else result[i] = - 1 ; // When none of elements in Stack are greater than arr[i%n] } stack.push(arr[i % n]); } for ( int i:result) { System.out.print(i + " " ); } } // Driver code public static void main (String[] args) { int [] arr = { 8 , 6 , 7 }; printNGE(arr); } } // This code is contributed by vaibhavpatel1904. |
Python3
# Function to find the Next Greater Element(NGE) def printNGE(a, n): s = [] ans = [ 0 ] * n for i in range ( 2 * n - 1 , - 1 , - 1 ): while s and a[i % n] > = s[ - 1 ]: s.pop() if i < n: if s: ans[i] = s[ - 1 ] else : ans[i] = - 1 s.append(a[i % n]) for i in range (n): print (ans[i], end = " " ) # Driver Code if __name__ = = "__main__" : # Given array arr[] arr = [ 8 , 6 , 7 ] N = len (arr) # Function call printNGE(arr, N) |
C#
// C# code for the above approach using System; using System.Collections; public class GFG { // Function to find the Next Greater Element(NGE) static void printNGE( int [] arr) { Stack stack = new Stack(); int n = arr.Length; int [] result = new int [n]; for ( int i = 2 * n - 1; i >= 0; i--) { // Remove all the elements in Stack that are // less than arr[i%n] while (stack.Count != 0 && arr[i % n] >= ( int )stack.Peek()) { stack.Pop(); } if (i < n) { if (stack.Count != 0) { result[i] = ( int )stack.Peek(); } else { // When none of elements in Stack are // greater than arr[i%n] result[i] = -1; } } stack.Push(arr[i % n]); } foreach ( int i in result) { Console.Write(i + " " ); } } static public void Main() { // Code int [] arr = { 8, 6, 7 }; printNGE(arr); } } // This code is contributed by lokesh. |
Javascript
<script> // Function to find the Next Greater Element(NGE) function printNGE(a, n){ let s = [] let ans = new Array(n).fill(0) for (let i=2 * n - 1;i>=0;i--){ while (s.length>0 && a[i % n] >= s[s.length - 1]) s.pop() if (i < n){ if (s.length>0) ans[i] = s[s.length-1] else ans[i] = -1 } s.push(a[i % n]) } for (let i=0;i<n;i++){ document.write(ans[i], " " ) } } // Driver Code // Given array arr[] let arr = [8, 6, 7] let N = arr.length // Function call printNGE(arr, N) // code is contributed by shinjanpatra </script> |
-1 7 8
Time Complexity: O(N)
Auxiliary Space: O(N)
Method :- 4
In method 3, next greater element is calculated by traversing the array from backward (end) but we can also do the same in forward (start) traversal.
C++
// C++ code to find the next greater element // in circular array. #include <bits/stdc++.h> using namespace std; // Function to find the Next Greater Element(NGE) void printNGE( int nums[], int n) { // Stores the next greater element for index i. vector< int > ans(n, -1); stack< int > s; for ( int i = 0; i < 2 * n; i++) { while (!s.empty() && nums[s.top()] < nums[i % n]) { ans[s.top()] = nums[i % n]; s.pop(); } if (i < n) s.push(i); } for ( auto it : ans) cout << it << " " ; } // Driver Code int main() { int arr[] = { 8, 6, 7 }; int N = sizeof (arr) / sizeof (arr[0]); printNGE(arr, N); return 0; } // This code is contributed by Aditya Kumar (adityakumar129) |
Java
/*package whatever //do not write package name here */ import java.io.*; import java.util.*; class GFG { public static void printNGE( int [] arr) { Stack<Integer> stack = new Stack<>(); int n = arr.length; int [] result = new int [n]; Arrays.fill(result,- 1 ); for ( int i = 0 ; i < 2 *n- 1 ; i++) { // Remove all the elements in Stack that are less than arr[i%n] while (!stack.isEmpty() && arr[i % n] > arr[stack.peek()]){ result[stack.peek()] = arr[i%n]; stack.pop(); } if (i < n) stack.push(i); } for ( int i:result) { System.out.print(i + " " ); } } // Driver code public static void main (String[] args) { int [] arr = { 8 , 6 , 7 }; printNGE(arr); } } // This code is contributed by isha307. |
Python3
# Python code for the above approach def printNGE(arr): stack = [] n = len (arr) result = [ - 1 ] * n for i in range ( 2 * n - 1 ): # Remove all the elements in Stack that are less than arr[i%n] while stack and arr[i % n] > arr[stack[ - 1 ]]: result[stack[ - 1 ]] = arr[i % n] stack.pop() if i < n: stack.append(i) for i in result: print (i, end = ' ' ) arr = [ 8 , 6 , 7 ] printNGE(arr) # This code is contributed by lokesh. |
C#
// C# code for the above approach using System; using System.Collections; using System.Collections.Generic; public class GFG { static void printNGE( int [] arr) { Stack stack = new Stack(); int n = arr.Length; int [] result = new int [n]; Array.Fill(result, -1); for ( int i = 0; i < 2 * n - 1; i++) { // Remove all the elements in Stack that are // less than arr[i%n] while (stack.Count != 0 && arr[i % n] > arr[( int )stack.Peek()]) { result[( int )stack.Peek()] = arr[i % n]; stack.Pop(); } if (i < n) stack.Push(i); } foreach ( int i in result) { Console.Write(i + " " ); } } static public void Main() { // Code int [] arr = { 8, 6, 7 }; printNGE(arr); } } // This code is contributed by lokeshmvs21. |
Javascript
<script> // JavaScript code to find the next greater element // in circular array. // Function to find the Next Greater Element(NGE) function printNGE(nums, n) { // Stores the next greater element for index i. let ans = new Array(n).fill(-1); let s = []; for (let i = 0; i < 2 * n; i++) { while (s.length > 0 && nums[s[s.length - 1]] < nums[i % n]) { ans[s[s.length - 1]] = nums[i % n]; s.pop(); } if (i < n) s.push(i); } for (let it of ans) document.write(it , " " ); } // Driver Code let arr = [ 8, 6, 7 ]; let N = arr.length; printNGE(arr, N); // This code is contributed by shinjanpatra </script> |
-1 7 8
Time Complexity: O(N)
Auxiliary Space: O(N)
Method 5: (Using Deque)
Intuition:
We can use a stack to find the next greater element of each element in the given array. We loop through the array twice to compare each element with every other element. For each element, we push its index onto the stack. If the current element is greater than the top element of the stack, we pop the stack and update the result array with the current element for the popped index. We continue this process until the stack is empty or the top element of the stack is greater than or equal to the current element. Finally, we return the result array.
C++
// C++ code to find the next greater element // in circular array. #include <bits/stdc++.h> using namespace std; // Function to find the Next Greater Element(NGE) void printNGE(vector< int >& nums,vector< int > &ret) { //declare a deque for accessing the elements deque< int > dq; //traverse throgh the entire vector and push the element into the deque for ( int i = 1; i < nums.size(); i++) dq.push_back(nums[i]); //check for the existence using two loops for ( int i = 0; i < nums.size(); i++) { int n = ret.size(); for ( int j = 0; j < dq.size(); j++) { if (dq[j] > nums[i]) { ret.emplace_back(dq[j]); break ; } } if (ret.size() == n) ret.emplace_back(-1); //push -1 at the end of vector dq.pop_front(); //pop if doesn'match dq.push_back(nums[i]); //push if matches } } // Driver Code int main() { vector< int > arr{ 8, 6, 7 }; //store the result in the res vector vector< int > res; printNGE(arr,res); for ( int i=0;i<res.size();i++){ cout<<res[i]<< " " ; } return 0; } |
Java
import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; class GFG { // Function to find the Next Greater Element (NGE) for each // element in the list 'nums' public static void printNGE(List<Integer> nums, List<Integer> ret) { // Create a deque (double-ended queue) to store elements for // finding NGE Deque<Integer> dq = new ArrayDeque<>(); // Add all elements from index 1 to the deque (except for the first element) // We start from index 1 because there is no element to the left of the first element. for ( int i = 1 ; i < nums.size(); i++) { dq.add(nums.get(i)); } // Iterate through each element in 'nums' to find its NGE for ( int i = 0 ; i < nums.size(); i++) { int n = ret.size(); // Iterate through the elements in the deque to // find the NGE for the current element in 'nums' for ( int j = 0 ; j < dq.size(); j++) { // If the top element of the deque is greater than // the current element in 'nums', // it is the Next Greater Element, so add it to the // 'ret' list and break the loop. if (dq.peek() > nums.get(i)) { ret.add(dq.peek()); break ; } // If the top element of the deque is not the NGE, // move it to the end of the deque dq.add(dq.poll()); } // If the NGE is not found (the loop didn't break), // add -1 to the 'ret' list as there is no greater element. if (ret.size() == n) { ret.add(- 1 ); } // Remove the first element from the deque // (which was used for finding the NGE) dq.pollFirst(); // Add the current element from 'nums' to the end // of the deque for the next iteration. dq.add(nums.get(i)); } } public static void main(String[] args) { List<Integer> arr = List.of( 8 , 6 , 7 ); List<Integer> res = new ArrayList<>(); // Find and store the Next Greater Element (NGE) for each // element in 'arr' in the 'res' list printNGE(arr, res); // Print the 'res' list containing the Next Greater // Element (NGE) for each element in 'arr' for ( int i = 0 ; i < res.size(); i++) { System.out.print(res.get(i) + " " ); } } } |
Python3
# Python code to find the next greater element # in circular array using deque # importing the module from collections import deque # main function which is finding the # next greater element (NGE) def print_NGE(nums): ret = [] # initializing a deque dq = deque() # iterating through the list # and adding elements in deque for i in range ( 1 , len (nums)): dq.append(nums[i]) # checking the existence of # duplicate values for i in range ( len (nums)): n = len (ret) for j in range ( len (dq)): if dq[j] > nums[i]: ret.append(dq[j]) break # appending -1 at the end if len (ret) = = n: ret.append( - 1 ) # popping if it doesn't match dq.popleft() # pushing if it matches dq.append(nums[i]) #returning the final result return ret # Driver Code arr = [ 8 , 6 , 7 ] res = print_NGE(arr) for i in range ( len (res)): print (res[i], end = " " ) |
C#
using System; using System.Collections.Generic; public class GFG { // Function to find the Next Greater Element (NGE) static void PrintNGE(List< int > nums, List< int > ret) { // Declare a deque for accessing the elements Queue< int > dq = new Queue< int >(nums.GetRange(1, nums.Count - 1)); // Traverse through the entire list and find the NGE for ( int i = 0; i < nums.Count; i++) { int n = ret.Count; foreach ( int num in dq) { if (num > nums[i]) { ret.Add(num); break ; } } if (ret.Count == n) ret.Add(-1); // Push -1 at the end of the list dq.Dequeue(); // Pop if it doesn't match dq.Enqueue(nums[i]); // Push if it matches } } // Driver Code public static void Main( string [] args) { List< int > arr = new List< int > { 8, 6, 7 }; // Store the result in the 'res' list List< int > res = new List< int >(); PrintNGE(arr, res); foreach ( int val in res) { Console.Write(val + " " ); } } } |
Javascript
// Function to find the Next Greater Element(NGE) function printNGE(nums, ret) { // Declare a deque for accessing the elements let dq = []; // Traverse through the entire array and push the elements into the deque for (let i = 1; i < nums.length; i++) { dq.push(nums[i]); } // Check for the existence using two loops for (let i = 0; i < nums.length; i++) { let n = ret.length; for (let j = 0; j < dq.length; j++) { if (dq[j] > nums[i]) { ret.push(dq[j]); break ; } } if (ret.length === n) { ret.push(-1); // Push -1 at the end of array } dq.shift(); // Pop if doesn't match dq.push(nums[i]); // Push if matches } } // Driver Code let arr = [8, 6, 7]; let res = []; printNGE(arr, res); for (let i = 0; i < res.length; i++) { console.log(res[i] + " " ); } |
-1 7 8
Time Complexity:O(n)
Auxiliary Space: O(n)