You get an integer array nums that is circular: after the last element, reading carries on from the first one again.
For each element, find the first value bigger than it that you meet when you walk forward from it, wrapping around the end if needed. Return these values in an array of the same length. When no bigger value exists anywhere, put -1 for that element.
Example 1
Input: nums = [3, 1, 4, 2] Output: [4, 4, -1, 3] Why: the last 2 wraps around and meets 3 first; 4 is the largest
2 more examples and the constraints
Example 2
Input: nums = [5, 5, 2] Output: [-1, -1, 5] Why: an equal value does not count as bigger
Example 3
Input: nums = [6] Output: [-1] Why: there is no other element to compare with
Constraints
- 1 ≤ nums.length ≤ 10,000
- -1,000,000,000 ≤ nums[i] ≤ 1,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan forward from each indexO(n²)
- Monotonic stack, two lapsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 elements | Verdict |
|---|---|---|---|
| Scan forward from each index | O(n²) | Simple, but rereads cells | |
| Monotonic stack, two laps | O(n) | Best; each index popped once |
n = length of nums.
Edge cases to test
- One element. [6] gives [-1]; there is nothing else to look at.
- All values equal. [7, 7, 7] gives [-1, -1, -1], because equal is not bigger.
- Answer only after wrapping. In [5, 4, 3, 2, 1] every value except 5 finds 5 by wrapping to the front.
- Several copies of the maximum. Every copy of the largest value gets -1, wherever it sits.
- Huge and negative values. Values span -1,000,000,000 to 1,000,000,000; compare them directly, and -1 can also be a real answer.
Common mistakes
- Walking the array only once, so values near the end never see the start of the array.
- Pushing indices again in the second lap, which can give an index two answers.
- Popping on
<=instead of<, which treats an equal value as bigger.
How to talk through it
- 1Clarify. Does an equal value count as bigger? What should be returned when nothing is bigger?
- 2Give the brute force. From each index walk forward with modulo until a bigger value appears: O(n²).
- 3Name the stack. Keep the indices still waiting; a new value answers every smaller one on top.
- 4Handle the circle. Loop i up to 2n and read nums[i % n], pushing only in the first lap.
- 5Test out loud. Run all-equal values and a falling array, where every answer comes from the wrap.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?