Nearest Smaller Element
Agoda interview questions · Medium · Coding round · 9 tests
Given an array of integers, return, for each element, the nearest element
to its left that is strictly smaller than it - or -1 if no such
element exists.
Interface
nearestSmallerElements(arr: number[]): number[]
Requirements
- Return an array the same length as the input.
- "Smaller" is strict - equal values do not count.
- The naive O(n²) approach (rescan left from every index) is not acceptable - there is a performance test that will time it out.
Example
Run your code with Ctrl+Enter to see results.