ENع
→Monotonic stacks
الدرس 09 · Linear structures in depth

Monotonic stacks and queues

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة11 خطوة5 أسئلةBeginner
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 9 · تفاعلي
01 / 11

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²)
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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²)
  2. 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)
  3. 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]
  4. 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]
  5. 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]
  6. 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]
  7. 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]
  8. 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]
  9. 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)
  10. 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]
  11. 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]

اختبار يتاح بعد الخطوة الأخيرة.