Previous Smaller Element

Given an integer array nums, return an array answer where answer[i] is the nearest element to the left of nums[i] that is strictly smaller than nums[i]. If no such element exists, put -1. Example: Input: nums = [4,5,2,10,8] Output: [-1,4,-1,2,2] Explanation: For 10, the nearest smaller value on the left is 2. For 8, it is also 2. Pattern focus: Monotonic Increasing Stack for Previous Smaller values.

Input Format

nums = array of integers

Output Format

answer[i] = nearest smaller value on the left, or -1 if none exists

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Examples

Example 1:

Input:

nums = [4,5,2,10,8]

Output:

[-1,4,-1,2,2]

Explanation:

Maintain an increasing stack so the top is the closest smaller element to the left.

Example 2:

Input:

nums = [3,1,2,4]

Output:

[-1,-1,1,2]

Explanation:

Each new number removes larger or equal values from the stack.

Loading...
Previous Smaller Element - Monotonic Stack Queue