|
| 1 | +// A Stack based C++ program to find next |
| 2 | +// greater element for all array elements |
| 3 | +// in same order as input. |
| 4 | +#include <bits/stdc++.h> |
| 5 | + |
| 6 | +using namespace std; |
| 7 | + |
| 8 | +/* prints element and NGE pair for all |
| 9 | +elements of arr[] of size n */ |
| 10 | +void printNGE(int arr[], int n) |
| 11 | +{ |
| 12 | + stack<int> s; |
| 13 | + unordered_map<int, int> mp; |
| 14 | + |
| 15 | + /* push the first element to stack */ |
| 16 | + s.push(arr[0]); |
| 17 | + |
| 18 | + |
| 19 | + // iterate for rest of the elements |
| 20 | + for (int i = 1; i < n; i++) { |
| 21 | + |
| 22 | + if (s.empty()) { |
| 23 | + s.push(arr[i]); |
| 24 | + continue; |
| 25 | + } |
| 26 | + |
| 27 | + /* if stack is not empty, then |
| 28 | + pop an element from stack. |
| 29 | + If the popped element is smaller |
| 30 | + than next, then |
| 31 | + a) print the pair |
| 32 | + b) keep popping while elements are |
| 33 | + smaller and stack is not empty */ |
| 34 | + while (s.empty() == false && s.top() < arr[i]) { |
| 35 | + mp[s.top()] = arr[i]; |
| 36 | + s.pop(); |
| 37 | + } |
| 38 | + |
| 39 | + /* push next to stack so that we can find |
| 40 | + next smaller for it */ |
| 41 | + s.push(arr[i]); |
| 42 | + } |
| 43 | + |
| 44 | + /* After iterating over the loop, the remaining |
| 45 | +elements in stack do not have the next smaller |
| 46 | +element, so print -1 for them */ |
| 47 | + while (s.empty() == false) { |
| 48 | + mp[s.top()] = -1; |
| 49 | + s.pop(); |
| 50 | + } |
| 51 | + |
| 52 | + for (int i=0; i<n; i++) |
| 53 | + cout << arr[i] << " ---> " << mp[arr[i]] << endl; |
| 54 | +} |
| 55 | + |
| 56 | +/* Driver program to test above functions */ |
| 57 | +int main() |
| 58 | +{ |
| 59 | + int arr[] = { 11, 13, 21, 3 }; |
| 60 | + int n = sizeof(arr) / sizeof(arr[0]); |
| 61 | + printNGE(arr, n); |
| 62 | + return 0; |
| 63 | +} |
0 commit comments