Skip to content
Related Articles

Related Articles

Improve Article
Find the next greater element in a Circular Array
  • Difficulty Level : Medium
  • Last Updated : 15 Jun, 2021

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 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 cicular 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;
}

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 cicular 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 Code_Mech

Python3




# Python3 program for the above approach
 
# Function to find the NGE
def printNGE(A, n):
 
    # Formation of cicular 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 cicular 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 prletNGE(A, n)
{
 
    // Formation of cicular 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;
            }
        }
             
        // Prlet the updated NGE
        document.write(next + ", ");
    }
}
 
 
// Driver Code
 
    // Given array arr[]
    let arr = [ 1, 2, 1 ];
 
    let N = arr.length;
 
    // Function call
    prletNGE(arr, N);
 
</script>
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 <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]) {
                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 yashbeersingh42

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>
Output
-1 7 8

 Time Complexity: O(n2
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes




My Personal Notes arrow_drop_up
Recommended Articles
Page :