Next Greater Element in a Circular Array (Medium)

Good evening! Here's our prompt for today.

You may see this problem at Microsoft, Vmware, Atlassian, Netflix, Reddit, Hudson River-trading, Glassdoor, Canva, Toast, Gitlab, Jfrog, Auth0, Automattic, Blend, Intel, and Sony.

A circular array is one where the next element of the last element is the first element.

You know how standard arrays look. Instead of [1, 2, 3, 4], imagine the following, where after index 7, we'd move back to index 0.

Description

Can you write a method nextLargerNumber(nums: array) to print the next immediate larger number for every element in the array?

Note: for any element within the circular array, the next immediate larger number could be found circularly-- past the end and before it. If there is no number greater, return -1.

Take the following example, with an analysis for each index:

JAVASCRIPT
1nextLargerNumber([3, 1, 3, 4])
2// [4, 3, 4, -1]
3// 3's next greater is 4
4// 1's next greater is 3
5// 3's next greater is 4 again
6// 4 will look to the beginning, but find nothing, so -1

Constraints

  • Length of the array <= 100000
  • The array will contain values between -1000000000 and 1000000000
  • Expected time complexity : O(n)
  • Expected space complexity : O(n)
JAVASCRIPT
OUTPUT
Results will appear here.