CSES Solutions – Nearest Smaller Values
Last Updated :
08 Mar, 2024
Given an array arr[] of N integers, your task is to find for each array position (1-based indexing) the nearest position to its left having a smaller value.
Examples:
Input: N = 8, arr[] = {2, 5, 1, 4, 8, 3, 2, 5}
Output: 0 1 0 3 4 3 3 7
Explanation:
- For 1st element 2, there is no smaller element on the left, therefore print 0.
- For 2nd element 5, the 1st element = 2 is the smaller element on the left, therefore print 1.
- For 3rd element 1, there is no smaller element on the left, therefore print 0.
- For 4th element 4, the 3rd element = 1 is the smaller element on the left, therefore print 3.
- For 5th element 8, the 4th element = 4 is the smaller element on the left, therefore print 4.
- For 6th element 3, the 3rd element = 1 is the smaller element on the left, therefore print 3.
- For 7th element 2, the 3rd element = 1 is the smaller element on the left, therefore print 3.
- For 8th element 5, the 7th element = 2 is the smaller element on the left, therefore print 3.
Input: N = 5, arr[] = {1, 2, 3, 2, 1}
Output: 0 1 2 1 0
Explanation:
- For 1st element 1, there is no smaller element on the left, therefore print 0.
- For 2nd element 2, the 1st element = 1 is the smaller element on the left, therefore print 1.
- For 3rd element 3, the 2nd element = 2 is the smaller element on the left, therefore print 2.
- For 4th element 2, the 1st element = 1 is the smaller element on the left, therefore print 1.
- For 5th element 1, there is no smaller element on the left, therefore print 0.
Approach: To solve the problem, follow the below idea:
The problem can be solved using a Monotonic Stack to store the indices of elements of arr[]. Monotonic Stack stores all the elements in a certain order(increasing or decreasing). We will use Monotonic Stack such that it stores indices and as we move from top to bottom, we have indices of decreasing elements. Iterate over the array arr[] and for each item, keep popping the indices from the top of our stack as long as value at index = top is greater than or equal to our current item. This is because any value greater than our current value won’t be the answer for any future items, since our current item is smaller and is located further to the right in the array.
If we find a position such that value at that position is less than our current item, we’ll set the answer for our current position to this position. This is because our stack keeps the most recently added (rightmost) items at the top, so this position will be the rightmost position with a value less than our current item.
Finally, we’ll add the current position to the stack.
Step-by-step algorithm:
- Initialize a stack, say prevSmaller that stores the indices of previous elements such that if we move from top to bottom, we have all the indices of decreasing elements.
- Iterate over all the indices from 0 to N – 1,
- Keep popping the indices from the top of our stack till value at index = top is >= current element.
- After popping, if the stack is empty then print 0.
- Otherwise, print the top of the stack + 1 (1-based indexing).
- Push the current index to the stack.
Below is the implementation of the algorithm:
C++
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
void solve(vector<ll>& arr, ll N)
{
stack<ll> prevSmaller;
for ( int i = 0; i < N; i++) {
while (!prevSmaller.empty()
&& arr[prevSmaller.top()] >= arr[i]) {
prevSmaller.pop();
}
if (prevSmaller.empty())
cout << 0 << " ";
else
cout << prevSmaller.top() + 1 << " ";
prevSmaller.push(i);
}
}
int main()
{
ll N = 8;
vector<ll> arr = { 2, 5, 1, 4, 8, 3, 2, 5 };
solve(arr, N);
return 0;
}
|
Java
import java.util.*;
public class Main {
static void solve(List<Long> arr, int N) {
Stack<Integer> prevSmaller = new Stack<>();
for ( int i = 0 ; i < N; i++) {
while (!prevSmaller.empty() && arr.get(prevSmaller.peek()) >= arr.get(i)) {
prevSmaller.pop();
}
if (prevSmaller.empty())
System.out.print( 0 + " " );
else
System.out.print(prevSmaller.peek() + 1 + " " );
prevSmaller.push(i);
}
}
public static void main(String[] args) {
int N = 8 ;
List<Long> arr = Arrays.asList(2L, 5L, 1L, 4L, 8L, 3L, 2L, 5L);
solve(arr, N);
}
}
|
Python
def solve(arr):
prev_smaller = []
for i in range ( len (arr)):
while prev_smaller and arr[prev_smaller[ - 1 ]] > = arr[i]:
prev_smaller.pop()
if not prev_smaller:
print 0 ,
else :
print prev_smaller[ - 1 ] + 1 ,
prev_smaller.append(i)
arr = [ 2 , 5 , 1 , 4 , 8 , 3 , 2 , 5 ]
solve(arr)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static void Solve(List< long > arr)
{
Stack< long > prevSmaller = new Stack< long >();
for ( int i = 0; i < arr.Count; i++)
{
while (prevSmaller.Count > 0 && arr[( int )prevSmaller.Peek()] >= arr[i])
{
prevSmaller.Pop();
}
if (prevSmaller.Count == 0)
Console.Write( "0 " );
else
Console.Write(prevSmaller.Peek() + 1 + " " );
prevSmaller.Push(i);
}
}
static void Main( string [] args)
{
List< long > arr = new List< long > { 2, 5, 1, 4, 8, 3, 2, 5 };
Solve(arr);
}
}
|
Javascript
function solve(arr) {
let prevSmaller = [];
for (let i = 0; i < arr.length; i++) {
while (prevSmaller.length > 0 && arr[prevSmaller[prevSmaller.length - 1]] >= arr[i]) {
prevSmaller.pop();
}
if (prevSmaller.length === 0)
process.stdout.write( "0 " );
else
process.stdout.write(prevSmaller[prevSmaller.length - 1] + 1 + " " );
prevSmaller.push(i);
}
}
const N = 8;
const arr = [2, 5, 1, 4, 8, 3, 2, 5];
solve(arr, N);
|
Time Complexity: O(N), where N is the size of arr[].
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...