Skip to content

Instantly share code, notes, and snippets.

@codecakes
Created October 21, 2021 11:40
Show Gist options
  • Save codecakes/959fd090d4082377b1ab2b57e3847b3a to your computer and use it in GitHub Desktop.
Save codecakes/959fd090d4082377b1ab2b57e3847b3a to your computer and use it in GitHub Desktop.
Next Greater Element Circular
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