Skip to content

Commit 7ac560f

Browse files
author
Joseph Luce
authored
Create 496_next_greater_element_I.md
1 parent eab84ae commit 7ac560f

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# 496. Next Greater Element I
2+
3+
## Stack Solution
4+
- Runtime: O(N)
5+
- Space: O(N)
6+
- N = Number of elements in both lists
7+
8+
This is an example of where a monotonic stack is useful.
9+
Monotonic stacks only contain elements that are increasing or decresing in value.
10+
11+
Therefore, in this case, we can have a stack that only has increasing values.
12+
For each number in nums2, if we encounter an element larger than the one on top of the stack, we can pop off the top of the stack and map the popped element with the current number as the next largest element.
13+
We continue popping and mapping until the stack is empty, then we can add the current number into the stack.
14+
At the end, we will have a mapping for each number in num2 with their next greater element using this method.
15+
16+
```
17+
from collections import defaultdict
18+
19+
class Solution:
20+
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
21+
22+
def get_greater_map():
23+
stack = list()
24+
greater_map = defaultdict(lambda:-1)
25+
for num in nums2:
26+
while len(stack) and num > stack[-1]:
27+
greater_map[stack.pop()] = num
28+
stack.append(num)
29+
return greater_map
30+
31+
greater_map = get_greater_map()
32+
result = list()
33+
for num in nums1:
34+
result.append(greater_map[num])
35+
return result
36+
```

0 commit comments

Comments
 (0)