InternDoor

The next bigger number to the right

Mediumarrays · stacks · monotonic stack

Reported in interviews at (where)

For every number in nums, find the first number to its right that is strictly larger than it.

Return an array of the same length holding those numbers, with -1 wherever no larger number follows.

Example 1
Input
nums = [4,1,7,3,7,2]
Output
[7,7,-1,7,-1,-1]

After 4 the first bigger number is 7, and the same 7 is first for 1. Nothing after the first 7 is bigger than 7; for 3 the second 7 is. Nothing follows 2.

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

Equal is not bigger.

Example 3
Input
nums = [1,2,3]
Output
[2,3,-1]

In a rising array each number is answered by its neighbour.

Limits

  • 1 <= nums.length <= 100000
  • 0 <= nums[i] <= 1000000000

Hints

Hint 1

Checking every pair is O(n^2). Walk from the right instead, keeping the numbers that could still be someone's answer.

Hint 2

Keep them on a stack. Before using the top for nums[i], pop everything that is not bigger than nums[i]: it can never be the answer for anything further left either.

Where this was reported

Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.

Run your code to check it on the examples. Submit runs every hidden test.

Ready for the real one?

Engineering internships and entry-level jobs in India, newest first.