write a c program to find next greater element in an array. For example if the given array is { 2, 3, 9, 6, 4, 8, 7 }. The next greater of 2 is 3 , for 3 is 9 , for 6 is 8, for 4 is 8. There is no next greater element for 8 and 7. In case of no next greater element found ,print -1.
find next greater element in an array ( method 1)
#include<iostream> #include<algorithm> #include<stack> using namespace std; int arr[] = { 2, 3, 9, 6, 4, 8, 7 }; void method_1(int size_of_arr); int main() { int size_of_arr = sizeof(arr) / sizeof(arr[0]); method_1(size_of_arr); cout << "\n"; return 0; } // with O(n square) complexity void method_1(int arr_size) { int i = 0; int j = 0; cout << "The next greater of\n"; for (i = 0; i < arr_size; i++) { // save ith num int a = arr[i]; int found = 0; // search for next greater for (j = i + 1; j < arr_size; j++) { if (arr[j] > a) { cout << a << ": is " << arr[j] << endl; found = 1; break; } } // if not found next greater print -1 if (!found) cout << a << ": is " << "-1" << endl; } }
The time complexity of above solution is O(N²). So this method is not an efficient solution. this problem can be solved by using stack with O(N) complexity.
C++ Solution using stack with O(N) complexity
#include<iostream> #include<algorithm> #include<stack> using namespace std; int arr[] = { 2,3,9,6,4,8,7 }; //// by using stack with O(n) complexity void method_2(int arr_size); int main() { int size_of_arr = sizeof(arr) / sizeof(arr[0]); method_2(size_of_arr); return 0; } int pop(stack<int> &s) { int a = s.top(); s.pop(); return a; } int peek(stack<int> &s) { if(!s.empty()) return s.top(); return 0; } void method_2(int arr_size) { stack<int> s; s.push(arr[0]); cout << "The next greater of\n"; for (int i = 1; i < arr_size; i++) { while (!s.empty() && peek(s) < arr[i]) { cout << pop(s) << " : " << arr[i] << endl; } s.push(arr[i]); } while (!s.empty()) { int top = pop(s); cout << top << " : " << "-1" << endl; } }
How it works:
- Push the 0th element from array to the stack.
- Traverse array from 1st element to the end of array.
- During traversing , peek the top element of stack and compare with current element of array.
- if the current element of array is greater than the top element of the stack. then the next greater of top element of stack is current element of array. (pop the stack)
- Continue step 4 until the current element of array is greater than the top element of the stack.
- if the current element of array is lesser than the top element of the stack, push current element of array to the stack.
- When traversing ends and if the stack is not empty , it means all the elements in the stack are not having next greater.
Here are pictorial represents of above steps:
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
ref:
https://www.hackerrank.com/contests/second/challenges/next-greater-element
WE RECOMMEND RELATED POST
The post find next greater element in an array appeared first on wikistack.