MCPcopy Create free account
hub / github.com/ashishps1/awesome-leetcode-resources / MonotonicStack

Class MonotonicStack

patterns/python/monotonic_stack.py:1–26  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class MonotonicStack:
2 def next_greater_element(self, nums):
3 n = len(nums)
4 result = [-1] * n # Default to -1 if no greater element exists
5 stack = [] # Stack stores indices
6
7 for i in range(n):
8 while stack and nums[i] > nums[stack[-1]]:
9 index = stack.pop()
10 result[index] = nums[i]
11 stack.append(i)
12
13 return result
14
15 def daily_temperatures(self, temperatures):
16 n = len(temperatures)
17 result = [0] * n # Result array initialized with 0s
18 stack = [] # Monotonic decreasing stack
19
20 for i in range(n):
21 while stack and temperatures[i] > temperatures[stack[-1]]:
22 prev_index = stack.pop()
23 result[prev_index] = i - prev_index
24 stack.append(i)
25
26 return result

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected