The "Double Array" Trick
A circular array can be simulated by simply duplicating the array and placing the copy right next to the original: `[1, 2, 1]` becomes `[1, 2, 1, 1, 2, 1]`.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
How do you find the Next Greater Element when the array is circular? (i.e., the next element after the last is the first element).
A circular array can be simulated by simply duplicating the array and placing the copy right next to the original: `[1, 2, 1]` becomes `[1, 2, 1, 1, 2, 1]`.
Instead of actually using extra memory to duplicate the array, we can just run our loop from `2*N - 1` down to `0` and use the modulo operator `i % N` to access elements.
When `i >= N`, we are just pushing elements onto the stack so that when `i < N`, the stack is already populated with the "circular" elements that would appear to the right.