Python coding

Next greater value around a circle

The values in nums sit around a circle: after the last one you come back to the first. For each value, walk forward around the circle and return the first value you meet that is strictly greater, or None (shown as null) if there is none, as for the largest value. The result has one entry per value, in the same order.

Values may repeat and may be negative; nums may be empty. Aim for O(n): walking forward from every value is O(n²).

Besides the tests, one large input (4,500 values) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • next_greater_circular([1,2,1]) → [2,null,2]
  • next_greater_circular([3,8,4,1,2]) → [8,null,8,2,3]
  • next_greater_circular([5,4,3,2,1]) → [null,5,5,5,5]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Without the circle this is next greater element: a stack of indexes whose values never increase, popped when a bigger value arrives. The circle only adds the values before each index.

Hint 2

Loop i from 0 to 2n - 1 and read nums[i % n]: the second lap lets the indexes left on the stack meet the values before them. Push indexes only on the first lap.

Solution and why it works
pythonO(n) · O(n)
def next_greater_circular(nums: list[int]) -> list[int | None]:
    n = len(nums)
    answer, stack = [None] * n, []       # stack: indexes still waiting, values non-increasing
    for i in range(2 * n):               # two laps: the end of the list can see its start
        x = nums[i % n]
        while stack and nums[stack[-1]] < x:
            answer[stack.pop()] = x      # x is the first greater value after that index
        if i < n:
            stack.append(i)              # the second lap only answers, it adds nothing
    return answer

Each index waits on the stack until a greater value arrives, and the waiting values never increase, so the newest waiter is the first one a bigger value can answer. One lap misses answers that wrap around: a second lap over nums[i % n] lets the waiters near the end meet the start, without pushing anything twice. Each index is pushed once and popped at most once: O(n). Pop on <, not <=: an equal value isn't greater.