Next Smaller Element
Problem Statement
You are given an integer array arr. For every element, find its next smaller element: the first element to its right that is strictly smaller than it.
If no element to the right is smaller, the answer for that position is -1.
Write nextSmallerEle(arr) that returns these answers as an array of the same length.
An integer array arr of length n.
An array ans of length n, where ans[i] is the first value to the right of arr[i] that is smaller than arr[i], or -1.
For 4, the values to the right are 8, 5, 2, 25; the first one below 4 is 2. For 8 it is 5. For 5 it is 2. Nothing to the right of 2 is smaller, and 25 is last.
13 → 7, 7 → 6. Nothing after 6 is smaller. 12 is last.
An equal value is not smaller, so nobody has an answer.
- • 1 ≤ arr.length ≤ 10^5
- • 1 ≤ arr[i] ≤ 10^5
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each element, walk right until a strictly smaller value
Scan right to left; pop candidates ≥ current, top is the answer, push current
For every i, look at i + 1, i + 2, … and stop at the first value that is < arr[i]. If you reach the end, the answer is -1.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Monotonic Stack translate into production architectures and low-level memory mechanics.