Knew immediately this was a monotonic stack problem but explaining WHY took me longer than it should have.
Use a monotonic stack to efficiently find the next smaller element to the right for each index. Traverse the array from right to left, maintaining a stack of indices with increasing values, and for each element, pop indices until the top has a smaller value, then compute the distance. This achieves O(N) time and O(N) space.
Pro tip: Clarify the definition of 'first smaller value to its right' and confirm whether the distance is measured in indices or steps; also mention that the stack stores indices, not values, to easily compute distances.
Restate the problem: for each element, find the index distance to the nearest smaller element to its right, or 0 if none. Note the requirement to do better than O(N^2).
Select a monotonic stack to keep track of potential next smaller elements. The stack will store indices and maintain increasing values from top to bottom.
Iterate through the array starting from the last index. For each element, pop from the stack while the top element's value is greater than or equal to the current element.
If the stack is not empty, the top index is the next smaller element; compute the distance as top - current index. If empty, distance is 0. Then push the current index onto the stack.
Explain that each element is pushed and popped at most once, giving O(N) time and O(N) space. Discuss edge cases like all increasing, all decreasing, or duplicate values.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.