
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Next greater element in same order as input 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 and an array.
Iterate from the end of the array.
Remove the elements from the stack until it empty and the top element is less than or equal to the current element.
If the stack is empty, then there is no next greater element. So add -1 to the result array.
If the stack is not empty, then the top element is the next greater element for the current element. Add it to the result array.
Push the current element to the stack.
Iterate over the result array and print each element along with its next greater element.
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; int result[n]; for (int i = n - 1; i >= 0; i--) { while (!s.empty() && s.top() <= arr[i]) { s.pop(); } if (s.empty()) { result[i] = -1; }else { result[i] = s.top(); } s.push(arr[i]); } for (int i = 0; i < n; i++) { cout << arr[i] << " -> " << result[i] << endl; } } 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 Articles
- Next Greater Element in C++
- Next Greater Element II in C++
- Next Greater Element III in C++
- Next Greater Element in Circular Array in JavaScript
- Find next greater number with same set of digits in C++
- Finding distance to next greater element in JavaScript
- Elements greater than the previous and next element in an Array in C++
- Find next Smaller of next Greater in an array in C++
- Next Smaller Element in C++
- Next greater Number than N with the same quantity of digits A and B in C++
- Previous greater element in C++
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- Next Larger element in n-ary tree in C++
- Find the Next perfect square greater than a given number in C++
- Next greater integer having one more number of set bits in C++
