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
Current lesson

Next Greater Element Lab

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]
Open deeper structure lesson
1.0x