
- 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 II in C++
Suppose we have a circular array (the next element of the last element is the first element of the array), we have to display the Next Greater Number for every element. Here the Next Greater Number of a number x is the first greater number to its traversing-order next in the array, this means we could search circularly to find its next greater number. If it is not present, then it will be -1. So if the numbers are [1, 2, 1, 3, 2, 1], then output will be: [2,3,3,-1,3,2]
To solve this, we will follow these steps −
- n := size of array
- define one array called res, of size n, and fill this with -1, define one stack st
- for i in range 0 to 2n
- index := i mod n, x := nums[index]
- while st is not empty and nums[top of stack] < x
- res[top of stack] := x
- delete the top element from the stack
- insert index into the stack
- return res
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> nextGreaterElements(vector<int>& nums) { int n = nums.size(); vector <int> res(n, - 1); stack <int> st; for(int i = 0; i < 2 * n; i++){ int idx = i % n; int x = nums[idx]; while(!st.empty() && nums[st.top()] < x){ res[st.top()] = x; st.pop(); } st.push(idx); } return res; } }; main(){ Solution ob; vector<int> v = {1,2,1,3,2,1}; print_vector(ob.nextGreaterElements(v)); }
Input
[1,2,1,3,2,1]
Output
[2,3,3,-1,3,2]
- Related Articles
- Next Greater Element 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++
- Elements greater than the previous and next element in an Array in C++
- Find next Smaller of next Greater in an array in C++
- Interesting Python Implementation for Next Greater Elements
- Next Smaller Element in C++
- Finding next greater node for each node in JavaScript
- jQuery element + next Selector
- 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++

Advertisements