Skip to content

Commit 9cd6d74

Browse files
authored
Merge pull request #432 from Krishna200608/feature/issue-378-nearest-smaller-values
Solved Issue #378: Added solution for Nearest Smaller Values
2 parents ece83c4 + 910d3a1 commit 9cd6d74

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
Problem: Nearest Smaller Values
3+
Link: https://cses.fi/problemset/task/1645
4+
Author: Krishna Sikheriya (Krishna200608)
5+
6+
Short Problem Statement:
7+
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+
using namespace std;
35+
36+
int main() {
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)) return 0;
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
54+
// We only care about smaller values to the left
55+
while (!s.empty() && s.top().first >= a[i]) {
56+
s.pop();
57+
}
58+
59+
if (s.empty()) {
60+
cout << 0 << " ";
61+
} else {
62+
cout << s.top().second << " ";
63+
}
64+
65+
// Push current element (value, index) to stack
66+
s.push({a[i], i + 1});
67+
}
68+
cout << endl;
69+
70+
return 0;
71+
}
72+
73+
/*
74+
SUBMISSION LINK:
75+
https://cses.fi/paste/b62e11edd0054b5cf11189/
76+
*/

0 commit comments

Comments
 (0)