Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the next smaller element

For each element in an array, find the next smaller element to its right using a monotonic stack.

Python practice15 minStacks & QueuesIntermediateLast updated March 27, 2026

Problem statement

Given a list of integers nums, return a list result of the same length where result[i] is the next smaller element to the right of nums[i]. If no such element exists, result[i] should be -1. Aim for an O(n) time solution using a stack that maintains a monotonic increasing sequence of values (or their indices).

Task

Implement next_smaller(nums) that returns a list where each position contains the first smaller element to the right, or -1 if none.

Examples

Basic example

Input

[4, 5, 2, 25]

Output

[2, 2, -1, -1]

For 4 the next smaller is 2; for 5 it's 2; for 2 none; for 25 none.

Input format

A single list of integers, e.g. [4, 5, 2, 25].

Output format

A list of integers of same length, e.g. [2, 2, -1, -1].

Constraints

0 <= len(nums) <= 10^5; -10^9 <= nums[i] <= 10^9; expected O(n) time and O(n) extra space.

Samples

Sample 1

Input

[3, 7, 1, 7, 2]

Output

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

For 3 the next smaller is 1, for 7 it's 1, 1 has none, for the next 7 it's 2, for 2 none.