intermediate · monotonic stack · circular array
Next bigger value on a ring
Problem
Numbers are written around a ring, given in clockwise order starting anywhere. For each number, find the first strictly larger number met when walking clockwise from it (wrapping past the end back to the start). Write −1 when no larger number exists anywhere on the ring.
Constraints
- 1 ≤ n ≤ 20
- values from 0 to 999
Examples
[3, 8, 4, 1] → [8, -1, 8, 3] — From 4, walking clockwise passes 1 and wraps to 3, then 8. From 1 the walk wraps to 3.
Show the solution
Monotonic stack over two laps
The stack holds indices whose answer is still unknown, with values non-increasing from bottom to top. A new value answers exactly the waiting values smaller than it. A second lap lets values near the end see the values at the start.
Why it is correct
Invariant: the stack holds the unresolved indices in order, with non-increasing values. When value v at step s arrives, any waiting index with a smaller value has not met a larger value since it was pushed (it would have been popped), so v is its first larger value clockwise. During the second lap the walk from any index has passed every other position once, so any index still on the stack afterwards has no larger value on the ring: −1.
Complexity
Time O(n), extra space O(n). There are 2n steps; each index is pushed once and popped at most once, so the inner loop runs at most n times in total.
For contrast: From each index, walk clockwise up to n − 1 steps until a larger value appears. That costs O(n²) time and O(1) space.
Edge cases
- One value: −1.
- All equal: all −1 (strictly larger is required).
- The maximum always gets −1.
Common mistakes
- Pushing again in the second lap, which makes indices wait for themselves.
- Using ≤ instead of < and resolving equal values.
Step through it
The solution in four languages
Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.
namespace Bekadan.Dsa.Examples.Problems;
public static class NextGreaterCircular
{
/// <summary>For each value on a ring, the first strictly larger value clockwise, or -1. Monotonic stack over two laps: O(n).</summary>
public static int[] Compute(int[] values)
{
int n = values.Length;
var answer = new int[n];
Array.Fill(answer, -1);
var waiting = new Stack<int>(); // indices still looking; values non-increasing bottom to top
for (int step = 0; step < 2 * n; step++) // the second lap only resolves
{
int i = step % n;
while (waiting.Count > 0 && values[waiting.Peek()] < values[i])
{
answer[waiting.Pop()] = values[i];
}
if (step < n) waiting.Push(i);
}
return answer;
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/NextGreaterCircular.cs
from collections.abc import Sequence
def compute(values: Sequence[int]) -> list[int]:
"""For each value on a ring, the first strictly larger value clockwise, or -1. Monotonic stack over two laps: O(n)."""
n = len(values)
answer = [-1] * n
waiting: list[int] = [] # indices still looking; values non-increasing bottom to top
for step in range(2 * n): # the second lap only resolves
i = step % n
while waiting and values[waiting[-1]] < values[i]:
answer[waiting.pop()] = values[i]
if step < n:
waiting.append(i)
return answer
Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/next_greater_circular.py
package dev.bekadan.dsa.problems;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
public final class NextGreaterCircular {
private NextGreaterCircular() {
}
/** For each value on a ring, the first strictly larger value clockwise, or -1. Monotonic stack over two laps: O(n). */
public static int[] compute(int[] values) {
int n = values.length;
int[] answer = new int[n];
Arrays.fill(answer, -1);
Deque<Integer> waiting = new ArrayDeque<>(); // indices still looking; values non-increasing bottom to top
for (int step = 0; step < 2 * n; step++) { // the second lap only resolves
int i = step % n;
while (!waiting.isEmpty() && values[waiting.peek()] < values[i]) {
answer[waiting.pop()] = values[i];
}
if (step < n) {
waiting.push(i);
}
}
return answer;
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/NextGreaterCircular.java
#pragma once
#include <cstddef>
#include <span>
#include <vector>
namespace bekadan::dsa::problems {
// For each value on a ring, the first strictly larger value clockwise, or -1. Monotonic stack over two laps: O(n).
inline std::vector<int> next_greater_circular(std::span<const int> values) {
const std::size_t n = values.size();
std::vector<int> answer(n, -1);
std::vector<std::size_t> waiting; // indices still looking; values non-increasing bottom to top
for (std::size_t step = 0; step < 2 * n; ++step) { // the second lap only resolves
const std::size_t i = step % n;
while (!waiting.empty() && values[waiting.back()] < values[i]) {
answer[waiting.back()] = values[i];
waiting.pop_back();
}
if (step < n) waiting.push_back(i);
}
return answer;
}
} // namespace bekadan::dsa::problems
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/next_greater_circular.hpp