Skip to content

Commit da5414b

Browse files
committed
Previous Smaller Element
1 parent e537b57 commit da5414b

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

Stack/PreviousSmallerElement.cpp

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#include <iostream>
2+
#include <stack>
3+
#include <vector>
4+
using namespace std;
5+
6+
vector<int> prevSmallerElement(vector<int> arr)
7+
{
8+
stack<int> s;
9+
vector<int> ans(arr.size(), 0);
10+
11+
for (int i = 0; i < arr.size(); i++)
12+
{
13+
while (s.size() > 0 && s.top() >= arr[i]) // removing invlaid values
14+
{
15+
s.pop();
16+
}
17+
18+
if (s.empty())
19+
{
20+
ans[i] = -1;
21+
}
22+
else
23+
{
24+
ans[i] = s.top();
25+
}
26+
27+
s.push(arr[i]);
28+
}
29+
30+
return ans;
31+
}
32+
33+
int main()
34+
{
35+
vector<int> arr = {3, 1, 0, 8, 6};
36+
37+
vector<int> ans = prevSmallerElement(arr);
38+
39+
for (int val : ans)
40+
{
41+
cout << val << " ";
42+
}
43+
cout << endl;
44+
45+
return 0;
46+
}

Stack/PreviousSmallerElement.exe

103 KB
Binary file not shown.

0 commit comments

Comments
 (0)