Given an array arr[], find the Previous Smaller Element (PSE) for every element in the array.
- The Previous Smaller Element of an element x is defined as the first element to its left in the array that is smaller than x.
- If no such element exists for a particular position, the PSE should be considered as -1.
Examples:
Input: arr[] = [1, 6, 2]
Output: [-1, 1, 1]
Explanation: For the first element 1, there is no element to its left, so the result is -1. For 6, the previous smaller element is 1. For 2, the previous smaller element is also 1, since it is the closest smaller number when looking left.Input: arr[] = [1, 5, 0, 3, 4, 5]
Output: [-1, 1, -1, 0, 3, 4]
Explanation:
For 1, no element on the left → -1
For 5, the previous smaller element is 1
For 0, no smaller element on the left → -1
For 3, the previous smaller element is 0
For 4, the previous smaller element is 3
For the last 5, the previous smaller element is 4
Table of Content
[Naive Approach] Using Nested Loops - O(n2) Time and O(1) Space
The idea is to use two loops: for each element, check the elements on its left to find the previous smaller one. If none exists, store -1.
#include <iostream>
#include <vector>
using namespace std;
vector<int> prevSmaller(vector<int>& arr){
int n = arr.size();
vector<int> result(n, -1);
// for each element, check all elements
// on the left
for (int i = 0; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
if (arr[j] < arr[i]) {
result[i] = arr[j];
break;
}
}
}
return result;
}
int main() {
vector<int> arr = {1, 5, 0, 3, 4, 5};
vector<int> ans = prevSmaller(arr);
for (int x : ans) cout << x << " ";
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int* prevSmaller(int arr[], int n) {
// allocate memory for result array
int* result = (int*)malloc(n * sizeof(int));
// initialize all PSEs as -1
for (int i = 0; i < n; i++) result[i] = -1;
for (int i = 0; i < n; i++) {
// check all elements on the left
for (int j = i - 1; j >= 0; j--) {
if (arr[j] < arr[i]) {
// first smaller element on the left
result[i] = arr[j];
break;
}
}
}
return result;
}
int main() {
int arr[] = {1, 5, 0, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int* result = prevSmaller(arr, n);
for (int i = 0; i < n; i++) {
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
import java.util.ArrayList;
class GfG {
static ArrayList<Integer> prevSmaller(int arr[]) {
int n = arr.length;
ArrayList<Integer> result = new ArrayList<>();
// initialize all as -1
for (int i = 0; i < n; i++) result.add(-1);
// for each element, check all elements
// on the left
for (int i = 0; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
if (arr[j] < arr[i]) {
result.