Monotonic stacks and queues
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
A stack whose values only ever fall from bottom to top solves "what is the next bigger number?" in one pass. Watch index blocks hop from the list [2, 7, 3, 1, 5, 4] onto a stack, get popped by a bigger number and fly to their answer cells. Then the same rule on a deque gives the maximum of every sliding window. The Software lessons "Arrays and lists" and "Stacks and queues" cover push, pop and the deque, and "Ring buffers and deques under the hood" in this module shows why a deque's ends are cheap.
The next greater element
For each number, find the first larger number to its right, or -1 if there is none. The bottom row shows the goal. Checking every later number takes up to n(n-1)/2 comparisons: 15 for six numbers, so O(n²).
a = [2, 7, 3, 1, 5, 4] goal [7, -1, 5, 5, -1, -1] brute force: for each i, scan a[i+1:] for the first bigger number on this list: 9 comparisons on a falling list of 6: 5 + 4 + 3 + 2 + 1 = 15 in general n(n-1)/2, which is O(n²)
اقرأ الدرس خطوة بخطوة
The next greater element
For each number, find the first larger number to its right, or -1 if there is none. The bottom row shows the goal. Checking every later number takes up to n(n-1)/2 comparisons: 15 for six numbers, so O(n²).
a = [2, 7, 3, 1, 5, 4] goal [7, -1, 5, 5, -1, -1] brute force: for each i, scan a[i+1:] for the first bigger number on this list: 9 comparisons on a falling list of 6: 5 + 4 + 3 + 2 + 1 = 15 in general n(n-1)/2, which is O(n²)Keep a falling stack
The fast way walks the list once with a stack of indices still waiting for an answer. Their values only fall from bottom to top, so the stack is monotonic: it only ever goes one way. ans starts as all -1.
line 2 ans = [-1] * len(a) [-1, -1, -1, -1, -1, -1] line 3 st = [] the stack, holds indices rule: before pushing x, pop every index whose value is < x so a[st[0]] > a[st[1]] > ... > a[st[-1]] (values fall) st.append(i) pushes, st.pop() takes the top (Python lists)Index 0: push
i = 0, x = 2. The stack is empty, so there is nothing to compare. Push index 0: the number 2 now waits for something bigger.
i = 0, x = 2: push 0 st = [0] values [2] ans = [-1, -1, -1, -1, -1, -1]7 answers 2
i = 1, x = 7. The top waits on 2, and 2 < 7, so 7 is the first bigger number after 2: pop index 0 and write ans[0] = 7. The stack is now empty, so push index 1.
i = 1, x = 7: a[0] = 2 < 7 → pop 0, ans[0] = 7 i = 1, x = 7: push 1 st = [1] values [7] ans = [7, -1, -1, -1, -1, -1]Smaller numbers wait
x = 3 is smaller than 7, and x = 1 is smaller than 3, so neither answers anyone. Push index 2, then index 3. The values on the stack, 7, 3, 1, still fall.
i = 2, x = 3: push 2 i = 3, x = 1: push 3 st = [1, 2, 3] values [7, 3, 1] ans = [7, -1, -1, -1, -1, -1]One number, two answers
i = 4, x = 5. Pop index 3 (1 < 5): ans[3] = 5. Pop index 2 (3 < 5): ans[2] = 5. The top now holds 7, which is not smaller, so stop and push index 4.
i = 4, x = 5: a[3] = 1 < 5 → pop 3, ans[3] = 5 i = 4, x = 5: a[2] = 3 < 5 → pop 2, ans[2] = 5 i = 4, x = 5: push 4 st = [1, 4] values [7, 5] ans = [7, -1, 5, 5, -1, -1]4 waits too
i = 5, x = 4. The top holds 5, and 5 is not smaller than 4, so nothing pops. Push index 5. The stack holds 7, 5, 4: still falling.
i = 5, x = 4: push 5 st = [1, 4, 5] values [7, 5, 4] ans = [7, -1, 5, 5, -1, -1]Leftovers keep -1
The loop ends. Indices 1, 4 and 5 are still waiting: no bigger number came after 7, 5, 4. Their answers stay -1, so ans = [7, -1, 5, 5, -1, -1].
st = [1, 4, 5] values [7, 5, 4] nothing bigger came later, so ans keeps -1 there line 8 return ans [7, -1, 5, 5, -1, -1] next_greater([2, 7, 3, 1, 5, 4]) == [7, -1, 5, 5, -1, -1]Why it is O(n)
The while loop sits inside the for loop, yet each index is pushed once and popped at most once. Here: 6 pushes and 3 pops. With n numbers that is at most 2n stack operations, so the whole pass is O(n).
pushes: 6 (one per index) pops: 3 (at most one per index) total: 9 ≤ 2n = 12 aggregate count (CLRS ch. 16): a pop needs an earlier push, so pops ≤ pushes = n over the whole run each operation is O(1), so the pass is O(n)A monotonic queue
Sliding window maximum: the largest number in each window of k = 3. A deque (double-ended queue) pops smaller or equal values from the back, so its front holds the maximum. out[0] = 7, written under a[2], its window's last index.
i = 0: append 0 i = 1: a[0] = 2 ≤ 7 → pop 0 (back) i = 1: append 1 i = 2: append 2 i = 2: window a[0..2] max = a[dq[0]] = 7 dq = deque([1, 2]) values [7, 3] out = [7]The front leaves the window
Slide right. 1 waits behind 3. Then 5 pops 1 and 3 from the back, and index 1 (the 7) is outside the window, so popleft removes it. out = [7, 7, 5, 5]. Each index enters once and leaves at most once: O(n).
i = 3: append 3 i = 3: window a[1..3] max = a[dq[0]] = 7 i = 4: a[3] = 1 ≤ 5 → pop 3 (back) i = 4: a[2] = 3 ≤ 5 → pop 2 (back) i = 4: append 4 i = 4: front 1 ≤ 4 − 3 → popleft i = 4: window a[2..4] max = a[dq[0]] = 5 i = 5: append 5 i = 5: window a[3..5] max = a[dq[0]] = 5 dq = deque([4, 5]) values [5, 4] out = [7, 7, 5, 5]
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01What does next_greater return for [4, 2, 6, 1]?
4 and 2 both wait on the stack until 6 arrives and pops them, so both answers are 6. Nothing bigger comes after 6 or 1, so they keep -1.
02Before pushing a new number x, the stack pops every index whose value is smaller than x. What is true of the values on the stack afterwards?
Everything smaller than x has gone, so x sits on top of something at least as big. That keeps the values falling from bottom to top: the stack is monotonic.
03Why does the stack store indices instead of the numbers themselves?
The value can always be read back as a[i], but only the index says where the answer goes. Two equal values at different places need different answer cells.
04There is a while loop inside the for loop. Why is next_greater still O(n), not O(n²)?
One iteration can pop many indices (5 popped two in the lesson), but an index can only be popped after it was pushed. Over the whole run there are n pushes and at most n pops, at most 2n operations in total.
05In window_max with k = 3, when does an index leave from the front of the deque?
Bigger numbers clear the back, as in the stack. The front only has to leave once the window has slid past it: in the lesson, index 1 (the 7) leaves at i = 4, when the window is a[2..4].
المسرد
- Stack
- A collection where items are added and removed at the same end, the top: last in, first out (LIFO).
- Monotonic stack
- A stack whose values only go one way from bottom to top, for example always falling. It stays that way because smaller values are popped before a new one is pushed.
- Next greater element
- For each item in a list, the first item to its right that is larger, or -1 if there is none.
- Deque
- A double-ended queue: items can be added and removed at both ends in about O(1) time. In Python, collections.deque.
- Monotonic queue
- A deque kept monotonic the same way. Its front holds the best item (here the largest) of the current window.
- Sliding window
- A run of k neighbouring items that moves one place right at a time through a list.
- Amortised cost
- The cost per operation averaged over a whole run of operations. One step may be slow, but the total over n steps is bounded.
الملاحظات والمصادر
- The stack holds indices, not values, so a pop knows which answer to fill in: ans[st.pop()] = x. Each block in the figure shows its index on top and its value below.
- The O(n) bound is an aggregate count, as in CLRS chapter 16 (the stack with MULTIPOP): every pop removes something an earlier push added, so over the whole run there are at most as many pops as pushes. One iteration of the for loop can still pop many times.
- next_greater pops on < so equal values keep waiting (it finds a strictly greater number). window_max pops on <= so the newer of two equal values stays; with < it would still be correct, just keep more indices.
- Python’s deque appends and pops at both ends in about O(1) time. In the figure the deque’s blocks never slide: after a popleft the front simply moves one place right, as in a ring buffer.
- window_max returns 4 maxima for 6 numbers (n - k + 1). In the figure each one is written under the last index of its window, so out[0] sits under a[2] and out[3] under a[5]; the cells under a[0] and a[1] stay empty.
- Both functions are real Python 3: next_greater([2, 7, 3, 1, 5, 4]) returns [7, -1, 5, 5, -1, -1] and window_max([2, 7, 3, 1, 5, 4], 3) returns [7, 7, 5, 5].
- Python tutorial §5.1.1: Using lists as stacks
- Python library: collections.deque
- Sedgewick and Wayne, Algorithms 4th ed., §1.3 Bags, Queues, and Stacks
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 16: Amortized Analysis
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 2: Data Structures and Dynamic Arrays
- MIT 6.046J Design and Analysis of Algorithms (Spring 2012), Lecture 11: Amortized analysis
اختبار يتاح بعد الخطوة الأخيرة.