Previous Greater Element for Each Array Position

Implement previousGreaterElement

Given an integer array arr, find, for every position, the nearest element to its left that is strictly greater than it — or -1 if no such element exists. Scanning backward from scratch for every position works but repeats a lot of comparisons unnecessarily. A monotonic stackA stack kept deliberately in sorted order (here, strictly decreasing from bottom to top) by discarding entries that a new arrival makes permanently unreachable as an answer. of strictly decreasing values fixes this in one left-to-right pass: whenever a new element arrives, everything smaller-or-equal sitting on top of the stack can never be anyone's "previous greater" answer again — the new, bigger, closer element would always be found first — so those entries are popped and discarded for good. Whatever survives on top after popping is exactly the answer for the current position.

Example 1:

Input: arr = [4,9,2,7,3]

Output: [-1,-1,9,9,7]

Example 2:

Input: arr = [6,1,9,4,2,9,3]

Output: [-1,6,-1,9,4,-1,9]

Example 3:

Input: arr = [10,2,10,3]

Output: [-1,10,-1,10]

+ 4 hidden test cases run on Submit.

Constraints:

  • 1 ≤ arr.length ≤ 15
  • 0 ≤ arr[i] ≤ 1000

arr =

[4, 9, 2, 7, 3]