Foundations
Linear Structures
Hashing
Array and String Patterns
Recursion, Search, and Sorting
Problem Solving Patterns
Algorithm Searching
Sorting Algorithms
Array Algorithms
Grid Algorithms
Linear Structure Algorithms
Hashing Algorithms
Recursion and Backtracking
Greedy Algorithms
Tree and Heap Algorithms
Graph Algorithms
Dynamic Programming Algorithms
String Algorithms
Math Algorithms
Keyboard ready
Space plays. Arrow keys step. R restarts.
LAB Next Greater Element Lab
Stacks and Queues
Problem shape
Beginner
3
2
1
stack
1
2
3
Core idea
Use a monotonic stack to find the next bigger value to the right.
Step 1 / 5
Problem shape
Stacks and Queues Beginner
Next Greater Element
Welcome to the Next Greater Element algorithm lab. Use a monotonic stack to find the next bigger value to the right. Use it when: Use for nearest greater/smaller element problems. The time complexity is O(n), and the space complexity is O(n). The pseudocode is: stack = empty for i from n - 1 down to 0 while stack not empty and stack.top <= a[i] pop answer[i] = stack.top or none push a[i] As you practice, track the state that changes and the condition that makes the algorithm stop.
Time
O(n)
Space
O(n)
Pseudocode
stack = empty
for i from n - 1 down to 0
while stack not empty and stack.top <= a[i]
pop
answer[i] = stack.top or none
push a[i] 1.0x