Data Structures19 sections · 729 units
Open in Course

Monotonic Stack Visualization

Step by step

Array: [2,1,2,4,3][2, 1, 2, 4, 3]. Process left to right, maintain decreasing stack. i=0i=0, val=22: stack empty, push 22. Stack: [2][2]

i=1i=1, val=11: 1<21 < 2, push 11.

Stack: [2,1][2, 1]

i=2i=2, val=22: 2>12 > 1, pop 11 (answer for index 11 is 22), push 22. Stack: [2,2][2, 2]

i=3i=3, val=44: 4>24 > 2, pop both 22s (answers are 44), push 44.

Stack: [4][4]

i=4i=4, val=33: 3<43 < 4, push 33. Stack: [4,3][4, 3]

Remaining elements (44 and 33) have no next greater.