Skip to content
Onsite

Closest Greater Element

MediumP3Coding

For each element of nums, find the closest element (by index distance) that is strictly greater than it. If a greater element exists on both sides at the same distance, take the one on the left. If no element is greater, the answer is -1.

Return the value found for each position.

Example 1

Input
nums = [1,3,2,4]
Output
[3,4,3,-1]
Why
For 2, the greater 3 (left) and 4 (right) are both at distance 1; the left one wins.

Example 2

Input
nums = [5,5,5]
Output
[-1,-1,-1]

Example 3

Input
nums = [4,1,2]
Output
[-1,4,4]

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Hints

Run checks the 3 visible tests, Submit all 11.