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:



  1. 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}

  2. Find the next greater element till N elements in the above array formed.
  3. If any greater element is found then print that element, else print “-1”.

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

2, -1, 2,

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

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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : SHIVAMSINGH67, Code_Mech