|
| 1 | +/* |
| 2 | +Problem Name: Nearest Smaller Values |
| 3 | +
|
| 4 | +Short Problem Statement: |
| 5 | +Given an array of n integers, for each position i, find the nearest position |
| 6 | +to the left that contains a strictly smaller value. |
| 7 | +If no such position exists, print 0 for that index. |
| 8 | +
|
| 9 | +Approach (Using Prefix Sums / Stack Concept): |
| 10 | +We process the array from left to right using a monotonic increasing stack. |
| 11 | +Each stack element stores: |
| 12 | +- the value |
| 13 | +- its 1-based index |
| 14 | +
|
| 15 | +For every element: |
| 16 | +1. Pop elements from the stack while they are greater than or equal to |
| 17 | + the current value (they cannot be the nearest smaller). |
| 18 | +2. If the stack becomes empty, no smaller element exists on the left → print 0. |
| 19 | +3. Otherwise, the top of the stack gives the nearest smaller value’s position. |
| 20 | +4. Push the current element with its index into the stack. |
| 21 | +
|
| 22 | +This ensures each element is pushed and popped at most once. |
| 23 | +
|
| 24 | +Time Complexity: |
| 25 | +O(n) |
| 26 | +
|
| 27 | +Space Complexity: |
| 28 | +O(n) |
| 29 | +
|
| 30 | +Example: |
| 31 | +Input: |
| 32 | +8 |
| 33 | +2 5 1 4 8 3 2 5 |
| 34 | +
|
| 35 | +Output: |
| 36 | +0 1 0 3 4 3 3 7 |
| 37 | +
|
| 38 | +Submission Link: |
| 39 | +https://cses.fi/problemset/result/15785248/ |
| 40 | +*/ |
| 41 | + |
| 42 | +#include <bits/stdc++.h> |
| 43 | +using namespace std; |
| 44 | + |
| 45 | +#define fastio() ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr) |
| 46 | +#define ll long long |
| 47 | +#define endl '\n' |
| 48 | + |
| 49 | +int main() { |
| 50 | + fastio(); |
| 51 | + |
| 52 | + ll n; |
| 53 | + cin >> n; |
| 54 | + |
| 55 | + vector<ll> a(n); |
| 56 | + for (ll i = 0; i < n; i++) { |
| 57 | + cin >> a[i]; |
| 58 | + } |
| 59 | + |
| 60 | + stack<pair<ll, ll>> st; |
| 61 | + |
| 62 | + for (ll i = 0; i < n; i++) { |
| 63 | + while (!st.empty() && st.top().first >= a[i]) { |
| 64 | + st.pop(); |
| 65 | + } |
| 66 | + |
| 67 | + if (st.empty()) { |
| 68 | + cout << 0 << " "; |
| 69 | + } else { |
| 70 | + cout << st.top().second << " "; |
| 71 | + } |
| 72 | + |
| 73 | + st.push({a[i], i + 1}); |
| 74 | + } |
| 75 | + |
| 76 | + return 0; |
| 77 | +} |
0 commit comments