You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given an array of n integers, find for each array position the nearest position to its left having a smaller value. If no such position exists, print 0.
8
+
9
+
Approach:
10
+
We use a Monotonic Stack to solve this in linear time.
11
+
The stack will store pairs of (value, index) and maintain an increasing order of values.
12
+
For each element in the array:
13
+
1. We pop elements from the stack that are greater than or equal to the current element, as they cannot be the nearest smaller value for the current or subsequent elements.
14
+
2. If the stack becomes empty, it means there is no smaller value to the left; we print 0.
15
+
3. If the stack is not empty, the top element is the nearest smaller value; we print its index.
16
+
4. We push the current element and its index onto the stack.
17
+
18
+
Time Complexity: O(n) - Each element is pushed and popped from the stack at most once.
19
+
Space Complexity: O(n) - In the worst case (increasing array), the stack stores all elements.
20
+
21
+
Example I/O:
22
+
Input:
23
+
8
24
+
2 5 1 4 8 3 2 5
25
+
26
+
Output:
27
+
0 1 0 3 4 3 3 7
28
+
*/
29
+
30
+
#include<iostream>
31
+
#include<vector>
32
+
#include<stack>
33
+
34
+
usingnamespacestd;
35
+
36
+
intmain() {
37
+
// Optimization for faster I/O operations
38
+
ios_base::sync_with_stdio(false);
39
+
cin.tie(NULL);
40
+
41
+
int n;
42
+
if (!(cin >> n)) return0;
43
+
44
+
vector<int> a(n);
45
+
for (int i = 0; i < n; ++i) {
46
+
cin >> a[i];
47
+
}
48
+
49
+
// Stack stores pairs of {value, 1-based index}
50
+
stack<pair<int, int>> s;
51
+
52
+
for (int i = 0; i < n; ++i) {
53
+
// Pop elements greater than or equal to current element
0 commit comments