Given an array of integers arr, find the nearest smaller element to the left of each element in the array.
For the element at index i, find the closest element to its left (among indices 0 to i - 1) that is strictly smaller than arr[i]. If no such element exists, use -1.
Return an array of the same length where the value at each index is the nearest smaller element to the left, or -1 if none exists.
Function Signature
def nearest_smaller_to_left(arr: list[int]) -> list[int]:
Rules
-
Smaller means strictly smaller. An equal value to the left does not count.
-
Nearest means the largest index
j < i
with
arr[j] < arr[i]
. The output at index
i
is the value
arr[j]
.
-
Use
-1
when no such element exists. Because values can be negative, a
-1
in the output can also be a real element value: for
arr = [-1, 0]
the expected output is
[-1, -1]
.
Constraints
-
1 <= len(arr) <= 10^5
-
-10^9 <= arr[i] <= 10^9
Examples
Input: arr = [4,5,2,10,8]
Output: [-1,4,-1,2,2]
Nothing is to the left of 4, and nothing to the left of 2 is smaller than 2, so both get -1. For 5 the nearest smaller value is 4, and for 10 and for 8 it is 2 (10 is not smaller than 8).
Input: arr = [3,2,1]
Output: [-1,-1,-1]
The array is strictly decreasing, so no element has a smaller value to its left.
Input: arr = [2,2,3,1,3]
Output: [-1,-1,2,-1,1]
The second 2 gets -1 because an equal value is not strictly smaller. The last 3 gets 1, which is the closest smaller value to its left.