Circular arrays break standard monotonic stack solutions. The fix: double pass with modulo.
This guide shows you the exact technique and when to use it.
TL;DR
Problem: Circular array means after last element, continue from first.
Solution: Iterate 2 * n times with modulo indexing.
Template:
for i in range(2 * n):
idx = i % n # Wrap around
while stack and nums[idx] > nums[stack[-1]]:
result[stack.pop()] = nums[idx]
# Only push in first pass
if i < n:
stack.append(idx)Why Single Pass Fails
Example:
nums = [5, 4, 3, 2, 1]
Single pass result: [-1, -1, -1, -1, -1]
Correct result: [-1, 5, 5, 5, 5] (wrapping around)Problem: Elements at end need to "see" elements at start.
The Double Pass Solution
def nextGreaterElements(nums):
"""
LeetCode #503: Next Greater Element II (Circular)
Time: O(n)
Space: O(n)
"""
n = len(nums)
result = [-1] * n
stack = []
# Iterate 2n times
for i in range(2 * n):
idx = i % n # Wrap around
while stack and nums[idx] > nums[stack[-1]]:
result[stack.pop()] = nums[idx]
# Only push in first n iterations
if i < n:
stack.append(idx)
return result
# Test
print(nextGreaterElements([5, 4, 3, 2, 1]))
# Output: [-1, 5, 5, 5, 5] ✓Why It Works
First pass (i=0 to n-1):
- Process elements normally
- Push all indices
Second pass (i=n to 2n-1):
- Process elements again (wraparound)
- Don't push (avoid duplicates)
- Find next greater for elements that wrap
When to Use
Use double pass for:
- ✅ Next Greater Element II (#503)
- ✅ Any circular array problem
- ✅ Problems mentioning "circular" or "wraparound"
Don't use for:
- ❌ Regular arrays (no wraparound)
- ❌ Sliding window (different technique)
Conclusion
Circular arrays: Iterate 2 * n times with modulo.
Template:
for i in range(2 * n):
idx = i % n
# ... process ...
if i < n:
stack.append(idx)Next steps:
Want to Practice LeetCode Smarter?
LeetCopilot is a free browser extension that enhances your LeetCode practice with AI-powered hints, personalized study notes, and realistic mock interviews — all designed to accelerate your coding interview preparation.
Also compatible with Edge, Brave, and Opera
