

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Next Greater Element in C++
The next greater element is the element that is first greater element after it. Let's see an example.
arr = [4, 5, 3, 2, 1]
The next greater element for 4 is 5 and the next greater element for elements 3, 2, 1 is -1 as there is no greater element after them.
Algorithm
Initialise the array with random numbers.
Initialise a stack.
Add first element to the stack.
Iterate through the element of the array.
If the stack is empty, add the current element to the stack.
While the current element is greater than the top element of the stack.
Print the top element with the next greater element as current element.
Pop the top element.
Add the element to the stack.
While stack is not empty.
Print the elements with next greater element as -1.
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; void nextGreaterElements(int arr[], int n) { stack<int> s; s.push(arr[0]); for (int i = 1; i < n; i++) { if (s.empty()) { s.push(arr[i]); continue; } while (!s.empty() && s.top() < arr[i]) { cout << s.top() << " -> " << arr[i] << endl; s.pop(); } s.push(arr[i]); } while (!s.empty()) { cout << s.top() << " -> " << -1 << endl; s.pop(); } } int main() { int arr[] = { 1, 2, 3, 4, 5 }; int n = 5; nextGreaterElements(arr, n); return 0; }
Output
If you run the above code, then you will get the following result.
1 -> 2 2 -> 3 3 -> 4 4 -> 5 5 -> -1
- Related Questions & Answers
- Next Greater Element II in C++
- Next Greater Element III in C++
- Next Greater Element in Circular Array in JavaScript
- Finding distance to next greater element in JavaScript
- Next greater element in same order as input in C++
- Find next Smaller of next Greater in an array in C++
- Elements greater than the previous and next element in an Array in C++
- Interesting Python Implementation for Next Greater Elements
- jQuery element + next Selector
- Next Smaller Element in C++
- Finding next greater node for each node in JavaScript
- Previous greater element in C++
- Remove next element using jQuery?
- Find next sibling element in Selenium, Python?
- Find next greater number with same set of digits in C++