'Next greater element using recursion

I have seen the problem of finding the next greater element for each element in an array and it can be easily solved using monotonic stack. But can it be solved using recursion?

For the input array [4, 5, 2, 25], the next greater elements for each element are as follows.

   4      -->   5           
   5      -->   25        
   2      -->   25       
   25     -->   -1    

Using stack

#include <bits/stdc++.h>

using namespace std;

void printNGE(int arr[], int n)
{
    stack<int> s;
    int res[n];
    for (int i = n - 1; i >= 0; i--) {
    
        if (!s.empty()) {
            while (!s.empty() && s.top() <= arr[i]) {
                s.pop();
            }
        }
        res[i] = s.empty() ? -1 : s.top();
        s.push(arr[i]);
    }
    for (int i = 0; i < n; i++)
        cout << arr[i] << " --> " << res[i] << endl;
}

int main()
{
    int arr[] = { 11, 13, 21, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);

    printNGE(arr, n);
    return 0;
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source