Skip to content
Algorithm in JavaScript
Frame

Monotonic Stack

배열에서 단조 스택을 활용해 O(N)으로 다음 더 큰(혹은 작은) 값을 찾는 패턴과 구현 팁을 정리

Oct 20, 2025 — monotonic-stack

Monotonic stack

const fn = (array) => {
const N = array.length;
const result = Array(N).fill(0);
const stack = [];
for (const [ index, value ] of array.entries()) {
// found larger value
while (stack.length && stack.at(-1)[1] < value) {
// 조건에 따라서 더 큰 값혹은 더 작은 값을 찾는다.
// while (stack.length && stack.at(-1)[1] > value) {
const [ lastIndex, lastValue ] = stack.pop();
result[lastIndex] = ...
}
// push current value to stack
stack.push([ index, value ])
}
return result;
}

기본 문제들

Reference