Skip to content

Commit f9fd5c6

Browse files
authored
Merge pull request #717 from Karnika06/Devincept8
Added Next greater element using stack problem
2 parents cd5f2b3 + 7dd0a4a commit f9fd5c6

File tree

2 files changed

+97
-110
lines changed

2 files changed

+97
-110
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/*
2+
Implementation of Next Greater Element problem using stack
3+
4+
Given an array, print the Next Greater Element (NGE) for every element.
5+
The Next greater Element for an element x is the first greater element on
6+
the right side of x in array. Elements for which no greater element exist,
7+
consider next greater element as -1.
8+
9+
For the input array [4, 5, 2, 25}, the next greater elements for each element are as follows.
10+
11+
Element --> NGE
12+
13+
4 --> 5
14+
5 --> 25
15+
2 --> 25
16+
25 --> -1 */
17+
18+
#include <cmath>
19+
#include <cstdio>
20+
#include <vector>
21+
#include <iostream>
22+
#include <algorithm>
23+
#include <stack>
24+
#include <bits/stdc++.h>
25+
using namespace std;
26+
27+
vector<int> NGE(vector<int> v)
28+
{
29+
vector<int> nge(v.size());
30+
stack<int> stk;
31+
for(int i=0;i<v.size(); i++)
32+
{
33+
while(!stk.empty() && v[i] > v[stk.top()])
34+
{
35+
nge[stk.top()]=i;
36+
stk.pop();
37+
}
38+
stk.push(i);
39+
}
40+
while(!stk.empty())
41+
{
42+
nge[stk.top()]=-1;
43+
stk.pop();
44+
}
45+
return nge;
46+
}
47+
48+
int main()
49+
{
50+
int n;
51+
cin >> n;
52+
vector<int> v(n);
53+
54+
for(int i=0;i<n;i++)
55+
cin >> v[i];
56+
57+
vector<int> nge= NGE(v);
58+
59+
for(int i=0; i<n; i++)
60+
cout<< v[i] << " " << (nge[i]== -1 ? -1 : v[nge[i]]) << endl;
61+
62+
return 0;
63+
}
64+
65+
/*
66+
67+
Test case 1:
68+
69+
Sample Input
70+
71+
4
72+
4 5 2 25
73+
74+
Sample Output
75+
76+
4 5
77+
5 25
78+
2 25
79+
25 -1
80+
81+
Test case 2:
82+
83+
Sample Input
84+
85+
4
86+
13 7 6 12
87+
88+
Sample Output
89+
90+
13 -1
91+
7 12
92+
6 12
93+
12 -1
94+
95+
Time Complexity: O(n)
96+
Space Complexity: O(n)
97+
*/

Strings/DecodeWaysII.java

Lines changed: 0 additions & 110 deletions
This file was deleted.

0 commit comments

Comments
 (0)