Find the next greater element in a Circular Array - GeeksforGeeks

20 Apr, 2022
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++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the NGEvoid 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 Codeint main(){    // Given array arr[]    int arr[] = { 1, 2, 1 };     int N = sizeof(arr) / sizeof(arr[0]);     // Function call    printNGE(arr, N);     return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to find the NGEstatic 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 Codepublic 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 Code_Mech
# Python3 program for the above approach # Function to find the NGEdef 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 codeif __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# program for the above approachusing System;class GFG{ // Function to find the NGEstatic 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 Codepublic 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
<script> // JavaScript program for the above approach // Function to find the NGEfunction 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
Java
Python3
C#
Javascript
// 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 Codeint 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 shivanisinghss2110
// 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 Codeint main(){    // Given array arr[]    int arr[] = { 8, 6, 7 };     int N = sizeof(arr) / sizeof(arr[0]);     // Function call    printNGE(arr, N);     return 0;}
// Java program to demonstrate the// use of circular array without// using extra memory spaceimport 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 Codepublic 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 yashbeersingh42
# 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 callprintNGE(arr, N) # This code is contributed by divyeshrabadia07
// C# program to demonstrate the// use of circular array without// using extra memory spaceusing 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
<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++
Java
Python3
Javascript
#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 Codeint main(){    int arr[] = { 8, 6, 7 };    int N = sizeof(arr) / sizeof(arr[0]);    printNGE(arr, N);    return 0;}
/*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.
# 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 Codeif __name__ == "__main__":    # Given array arr[]    arr = [8, 6, 7]     N = len(arr)     # Function call    printNGE(arr, N)
<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 callprintNGE(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++
Javascript
// 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 Codeint 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)
<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 Codelet 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)
SHIVAMSINGH67
Code_Mech
tushar1247
yashbeersingh42
divyesh072019
divyeshrabadiya07
susmitakundugoaldanga
suresh07
CoderSaty
shivanisinghss2110
varshagumber28
surindertarika1234
vaibhavpatel1904
khushboogoyal499
amartyaghoshgfg
adityakumar129
shinjanpatra
circular-array
Greedy Algorithms
Algorithms
Arrays
Articles
Arrays
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Converting Roman Numerals to Decimal lying between 1 to 3999
Quick Sort vs Merge Sort
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Largest Sum Contiguous Subarray