Hints — p53 Next Greater Element II


Hint 1. “Circular” = the array wraps. After the last index, you continue searching from index 0. If you’ve gone all the way around without finding a strictly-greater value, the answer is -1.


Hint 2. Standard trick: double the array virtually by iterating from 0 to 2n - 1 and indexing with i % n. This gives every element a chance to be resolved by anything it might find in a full loop around.


Hint 3. Use the SAME monotonic decreasing stack of indices as p51/p52.


Hint 4. Critical detail: only push when i < n. Otherwise the same index would appear twice on the stack on the second pass, breaking the invariant and producing wrong answers.


Hint 5. After the 2n-iteration loop, anything STILL on the stack has had every position in the array attempt to resolve it; if none succeeded, the answer is genuinely -1 (and ans was pre-filled with -1).


If still stuck: see solution.py.