Skip to content

Commit 130ad49

Browse files
Update next_greater_element_i.cpp
1 parent 7091b83 commit 130ad49

File tree

1 file changed

+26
-18
lines changed

1 file changed

+26
-18
lines changed

next_greater_element_i.cpp

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
class Solution {
2-
public:
3-
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
1+
42
// Forward method
3+
// class Solution {
4+
// public:
5+
// vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
56
// unordered_map<int, int> ump; //to keep track of nge for each element in nums2
67
// //map of current element in stack => its nge
78
// stack<int> st; //to store right part of search
@@ -22,28 +23,35 @@ class Solution {
2223

2324
// return result;
2425

25-
//traverse backward
26-
if(nums1.size() == 0) return {};
26+
//Backward method (more readable and intuitive)
27+
class Solution {
28+
public:
29+
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
2730

28-
int n = nums2.size();
31+
int length = nums2.size(), j = 0;
32+
stack<int> st; //auxiliary
33+
unordered_map<int, int> subsetMap;
2934
vector<int> result;
3035

31-
stack<int> st;
32-
unordered_map<int, int> ump;
33-
34-
for(int i=n-1; i>=0; i--) {
36+
for(int i = length - 1; i >= 0; i--) {
37+
int element = nums2[i];
3538

36-
while(!st.empty() and st.top() < nums2[i]) st.pop();
37-
if(st.empty()) ump[nums2[i]] = -1;
38-
else ump[nums2[i]] = st.top();
39+
// if element = x, the nge for x will be 2x.. so remove all the x, x/2, x/4, ... elements from stack
40+
// top of stack represents next greater element seen so far
41+
while(!st.empty() and element > st.top())
42+
st.pop();
43+
44+
if(st.empty()) subsetMap[element] = -1;
45+
else subsetMap[element] = st.top();
3946

40-
st.push(nums2[i]);
47+
st.push(element);
4148
}
4249

43-
int m = nums1.size();
44-
for(auto num : nums1)
45-
result.push_back(ump[num]);
46-
50+
//since nums1 is subset of nums2; it is guaranteed that all elements of nums1 will be present in nums2
51+
for(auto element : nums1) {
52+
result.push_back(subsetMap[element]);
53+
}
4754
return result;
4855
}
4956
};
57+
};

0 commit comments

Comments
 (0)