Created
October 21, 2021 11:40
-
-
Save codecakes/959fd090d4082377b1ab2b57e3847b3a to your computer and use it in GitHub Desktop.
Next Greater Element Circular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def nextGreaterElement(array): | |
if not array: return [] | |
n = len(array) | |
if n == 1: | |
return [-1] | |
stack = [] | |
result = [-1 for _ in range(n)] | |
# fill next greater values - non circular, from stack | |
for long_idx in range(2*n): | |
idx = long_idx%n | |
num = array[idx] | |
while stack and array[stack[-1]] < num: | |
result[stack.pop()] = array[idx] | |
stack += [idx] | |
# print("stack", stack) | |
stack.clear() | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment