Previous Smaller Element for Each Array Position
Implement previousSmallerElement
Given an integer array
arr, find, for every position, the value of the nearest element strictly smaller than it to its left — or -1 if no such element exists.
Scanning backward from every position independently works but repeats a lot of comparisons that a smarter approach can skip entirely. The key insight: once a smaller value appears, every larger value sitting behind it becomes permanently irrelevant — no future position will ever "see past" the smaller, closer value to reach them. A monotonic stackMonotonic StackA stack maintained so its values stay in strictly increasing (or decreasing) order from bottom to top. Before pushing a new value, anything on top that would break that order gets popped off first — those popped values are provably never useful again. exploits exactly that: keep only values in increasing order, discarding anything that a smaller arrival has made obsolete, and whatever survives on top at each step is precisely the answer.
Example 1:
Input: arr = [7,3,9,2,6,1,8]
Output: [-1,-1,3,-1,2,-1,1]
Example 2:
Input: arr = [5,4,3,2,1]
Output: [-1,-1,-1,-1,-1]
Example 3:
Input: arr = [1,2,3,4,5]
Output: [-1,1,2,3,4]
+ 4 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ arr.length ≤ 15 - ●
0 ≤ arr[i] ≤ 1000
arr =
[7, 3, 9, 2, 6, 1, 8]