Concept
A stack kept in increasing or decreasing order answers "next greater element" and similar questions in O(n). Each element is pushed and popped at most once, however many comparisons it seems to need.
The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.
A few lines that show Monotonic stacks doing its job.
def next_greater(nums):
result = [-1] * len(nums)
stack = [] # indexes, values decreasing
for i, n in enumerate(nums):
while stack and nums[stack[-1]] < n:
result[stack.pop()] = n
stack.append(i)
return result
next_greater([2, 1, 5, 3]) # [5, 5, -1, -1]Pushing values instead of indexes. Most problems need the position or the distance to the answer, and a value alone cannot give it back.
Your roadmap puts these before Monotonic stacks, unless you already know them.
Once a session shows you understand Monotonic stacks, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.