# Find the next greater element in a Circular Array

• Difficulty Level : Medium
• Last Updated : 29 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++

 `// C++ program for the above approach` `#include ``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 ` `// 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

 ``

Output

`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 ``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 ` `// 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

 ``

Output

`-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 ``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 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)`

## Javascript

 ``

Output

`-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 ``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)`

## Javascript

 ``

Output

`-1 7 8 `

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

My Personal Notes arrow_drop_up