Notes
All notes

Stacks, Queues and Deques (DSA Core #3)

A stack is last-in-first-out, a queue is first-in-first-out, and a deque is both. Those three access rules are enough to build expression evaluators, undo history, BFS, and the two monotonic structures that wipe out most \(O(n^2)\) scans in array problems.

Stacks: the operations and where they show up

std::stack is an adapter over deque by default: push, pop, top, all \(O(1)\). It has no iterators, which is the point — you are only allowed to touch one end.

stack<int> st;
st.push(3);           // [3]
st.push(7);           // [3, 7]
int x = st.top();     // 7
st.pop();             // [3], returns void
bool empty = st.empty();

Applications that are genuinely LIFO:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=1.5cm, minimum height=0.6cm, font=\small\bfseries}]
  \foreach \v/\i in {3/0,7/1,1/2} \node[c, fill=blue!12] at (0,\i*0.62) {\v};
  \draw[thick] (-0.85,-0.35) -- (-0.85,1.9);
  \draw[thick] (0.85,-0.35) -- (0.85,1.9);
  \draw[thick] (-0.85,-0.35) -- (0.85,-0.35);
  \node[font=\scriptsize, anchor=west] at (1.0,1.24) {top (push/pop here)};
  \draw[->, thick] (2.6,1.55) -- (1.0,1.24);
  \node[font=\scriptsize, anchor=west] at (1.0,-0.05) {bottom};
\end{tikzpicture}

A stack is the right structure when the answer depends on the most recent unresolved thing. If it depends on the oldest, you want a queue.

QQuestionWhy does a stack have no iterators in the STL?
ASolution

Its contract is one-end access. Exposing iteration would let you violate the LIFO order, so the adapter deliberately omits it.

Queue and circular queue

A queue is push at the back, pop at the front, both \(O(1)\) with std::queue. The problem is the implementation: a naive array queue that increments head on every pop leaks space at the front. After n pops, the array is empty but you cannot push.

The fix is a circular buffer: head plus a count, and indices wrap modulo capacity.

class CircularQueue {
    vector<int> buf;
    int head = 0, cnt = 0;
public:
    explicit CircularQueue(int cap) : buf(cap) {}
    bool push(int x) {
        if (cnt == (int)buf.size()) return false;      // full
        buf[(head + cnt) % buf.size()] = x;
        ++cnt;
        return true;
    }
    bool pop() {
        if (cnt == 0) return false;                    // empty
        head = (head + 1) % buf.size();
        --cnt;
        return true;
    }
    int front() const { return buf[head]; }
    int back()  const { return buf[(head + cnt - 1) % buf.size()]; }
    bool empty() const { return cnt == 0; }
};

Two counters, not one: head and cnt distinguish full from empty. With only head and tail, a full buffer and an empty one look identical.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum size=0.7cm, font=\small\bfseries}]
  \foreach \i/\ang in {0/135,1/90,2/45,3/0,4/-45,5/-90,6/-135,7/-180}
    \node[c, fill=blue!10] at (\ang:1.5) {\i};
  \draw[->, very thick, orange] (135:2.2) -- (135:1.85);
  \node[font=\scriptsize, text=orange!80!black, anchor=east] at (135:2.25) {head};
  \draw[->, very thick, green!45!black] (225:2.2) -- (225:1.85);
  \node[font=\scriptsize, text=green!45!black, anchor=west] at (225:2.25) {tail};
  \node[font=\scriptsize, anchor=north] at (0,-2.05) {index = (head + i) mod 8};
\end{tikzpicture}

BFS is the canonical queue use: push the start, pop a node, push its unvisited neighbours. Because each node enters and leaves once, the total is \(O(V+E)\) (Ch. 6).

The other classic is the monotonic queue below, and the “recent counter” pattern (moving average from a data stream), which is a queue plus a running sum.

QQuestionWhy does a circular queue need a count field?
ASolution

head == tail is ambiguous: it means both empty and full. A count (or a deliberate one-slot gap) resolves it.

Deque

std::deque supports \(O(1)\) push and pop at both ends, plus random access. It is a list of fixed-size blocks, so it does not need one contiguous buffer and does not invalidate everything on growth.

Operation vector deque
push_back / pop_back \(O(1)\) amortized \(O(1)\)
push_front / pop_front \(O(n)\) \(O(1)\)
a[i] \(O(1)\) \(O(1)\), one extra indirection
Contiguous memory yes no

Use a deque for:

deque<int> dq;
dq.push_back(2);
dq.push_front(1);      // [1, 2]
dq.pop_front();        // [2]
dq.pop_back();         // []

For a fixed-size sliding window, a vector used as a circular buffer is usually faster than std::deque because of allocation and cache behaviour. A deque is still the simplest correct choice when the window size varies.

QQuestionWhen is deque the better default over vector?
ASolution

When you push and pop at both ends, or when you need stable references to elements that are not at the ends while the container grows.

Monotonic stacks

The pattern: keep a stack of indices whose values are increasing (or decreasing) from bottom to top. Before pushing a new element, pop everything that the new element resolves. Each index is pushed and popped once, so the total is \(O(n)\).

Next greater element is the smallest complete example:

vector<int> nextGreater(const vector<int>& a) {
    int n = (int)a.size();
    vector<int> res(n, -1);
    vector<int> st;                         // indices, values decreasing
    for (int i = 0; i < n; ++i) {
        while (!st.empty() && a[st.back()] < a[i]) {
            res[st.back()] = a[i];          // i is the next greater for st.back()
            st.pop_back();
        }
        st.push_back(i);
    }
    return res;
}

The invariant: values at indices in st are strictly decreasing from bottom to top, so the stack holds elements still waiting for a greater value. When a[i] arrives, it answers every waiting index with a smaller value, and those can never be answered later — their next greater is i.

a[st.back()] < a[i] versus <= is the whole difference between “next strictly greater” and “next greater or equal”. Pick per problem and write it in a comment.

Next smaller, and the other direction. Flip the comparison and the stack becomes increasing instead of decreasing:

vector<int> nextSmaller(const vector<int>& a) {
    int n = (int)a.size();
    vector<int> res(n, -1);
    vector<int> st;                          // indices, values increasing
    for (int i = 0; i < n; ++i) {
        while (!st.empty() && a[st.back()] > a[i]) {
            res[st.back()] = a[i];
            st.pop_back();
        }
        st.push_back(i);
    }
    return res;
}

Iterating right to left gives the same answers for the left side, so the four variants (greater/smaller, right/left) are one function with two changes: direction of the loop and direction of the comparison. For a circular array, loop 2n times and index with i % n, but only push indices < n.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.72cm, minimum height=0.62cm, font=\small\bfseries}]
  \foreach \v [count=\i from 0] in {2,1,5,4} \node[c] at (\i*0.8,0) {\v};
  \foreach \v/\i in {1/0,2/1} \node[c, fill=orange!25] at (0,\i*0.65+0.4) {\v};
  \node[font=\scriptsize, anchor=east] at (-0.5,0.4) {stack};
  \draw[->, thick, blue!60] (2.4,1.45) -- (1.55,0.95);
  \node[font=\scriptsize, text=blue!60!black, anchor=south] at (1.4,1.5) {5 answers both};
\end{tikzpicture}

Largest rectangle in histogram is the same stack with a sentinel and a width computation:

int largestRectangle(const vector<int>& h) {
    int n = (int)h.size(), best = 0;
    vector<int> st;                       // indices, heights increasing
    for (int i = 0; i <= n; ++i) {
        int cur = (i == n) ? 0 : h[i];    // sentinel flushes the stack
        while (!st.empty() && h[st.back()] >= cur) {
            int height = h[st.back()];
            st.pop_back();
            int left = st.empty() ? -1 : st.back();
            best = max(best, height * (i - left - 1));
        }
        st.push_back(i);
    }
    return best;
}

When a bar is popped, i is the first index to its right with a smaller height, and the new top is the first index to its left with a smaller height. The width is i - left - 1. Both boundaries are found in the same pass — that is the whole trick.

Variants: stock span, daily temperatures, sum of subarray minimums, trapping rain water, remove k digits to make the smallest number, and “132 pattern”.

QQuestionWhy is a monotonic stack \(O(n)\) when there is a while loop inside

a for loop?

ASolution

Each index is pushed once and popped at most once. The total number of pops across the whole run is at most n, so the inner loop is amortized \(O(1)\).

Monotonic queues

A monotonic queue answers “maximum of the last k elements” in \(O(1)\) amortized per element. Store indices, keep values decreasing, and evict from the front when an index leaves the window.

vector<int> maxSlidingWindow(const vector<int>& a, int k) {
    deque<int> dq;                        // indices, values decreasing
    vector<int> out;
    for (int i = 0; i < (int)a.size(); ++i) {
        while (!dq.empty() && dq.front() <= i - k) dq.pop_front();  // expired
        while (!dq.empty() && a[dq.back()] <= a[i]) dq.pop_back();  // dominated
        dq.push_back(i);
        if (i >= k - 1) out.push_back(a[dq.front()]);
    }
    return out;
}

Two evictions, two different reasons:

The front is always the maximum of the current window. Every index enters and leaves once, so the total is \(O(n)\) — compared to \(O(nk)\) for rescanning each window, which is \(10^{10}\) for \(n = 10^5, k = 10^5\).

Variant: for the minimum, reverse the comparison and keep values increasing. For “maximum of every subarray of size exactly k with a constraint”, combine with a prefix sum.

QQuestionWhy can the back-eviction pop an element that is still inside the

window?

ASolution

A newer element with a value at least as large dominates it: any window containing the old index also contains the new one, so the old value can never be the maximum again.

Expression evaluation

Two stacks or two passes. The standard route is infix → postfix (shunting-yard), then evaluate postfix left to right. Parentheses and precedence disappear in the first step.

Precedence: + - = 1, * / = 2, ( handled separately. Left-associative operators pop while the stack top has precedence greater than or equal, and that >= is what makes 8-3-2 evaluate to 3 rather than 7.

int prec(char op) {
    if (op == '+' || op == '-') return 1;
    if (op == '*' || op == '/') return 2;
    return 0;                                  // '('
}
string toPostfix(const string& s) {
    string out;
    vector<char> st;
    for (char c : s) {
        if (isdigit((unsigned char)c)) out += c;
        else if (c == '(') st.push_back(c);
        else if (c == ')') {
            while (!st.empty() && st.back() != '(') { out += st.back(); st.pop_back(); }
            if (!st.empty()) st.pop_back();     // drop '('
        } else {
            while (!st.empty() && prec(st.back()) >= prec(c)) {
                out += st.back(); st.pop_back();
            }
            st.push_back(c);
        }
    }
    while (!st.empty()) { out += st.back(); st.pop_back(); }
    return out;
}

Evaluation is one stack of numbers, and the order of the two pops matters:

int evalPostfix(const string& p) {
    vector<int> st;
    for (char c : p) {
        if (isdigit((unsigned char)c)) { st.push_back(c - '0'); continue; }
        int b = st.back(); st.pop_back();       // right operand
        int a = st.back(); st.pop_back();       // left operand
        switch (c) {
            case '+': st.push_back(a + b); break;
            case '-': st.push_back(a - b); break;   // a - b, not b - a
            case '*': st.push_back(a * b); break;
            case '/': st.push_back(a / b); break;
        }
    }
    return st.back();
}

a - b versus b - a is the classic silent wrong answer: with [5, 3, '-'] the result must be 2, and popping into a then b is what gets it right.

The other approach is one pass with two stacks (numbers and operators), applying an operator as soon as it is safe. Same precedence logic, fewer strings.

Not handled above, and usually not needed in an OA: multi-digit numbers, unary minus, spaces, and integer division truncation toward zero for negatives. If the problem has them, tokenize first, then run the same algorithm.

QQuestionWhy does left-associativity need prec(top) >= prec(c)?
ASolution

On a tie, the earlier operator must be applied first: in 8-3-2 the - on the stack has to fire before the new - is pushed.

Balanced parentheses

A stack of openers. On a closer, the top must be its match; at the end, the stack must be empty.

bool isValid(const string& s) {
    vector<char> st;
    for (char c : s) {
        if (c == '(' || c == '[' || c == '{') st.push_back(c);
        else {
            if (st.empty()) return false;
            char o = st.back(); st.pop_back();
            if ((c == ')' && o != '(') ||
                (c == ']' && o != '[') ||
                (c == '}' && o != '{')) return false;
        }
    }
    return st.empty();
}

Counting unmatched brackets gives the minimum number of insertions:

int minAddToMakeValid(const string& s) {
    int open = 0, add = 0;
    for (char c : s) {
        if (c == '(') ++open;
        else if (open > 0) --open;
        else ++add;              // unmatched ')'
    }
    return add + open;           // unmatched ')' plus leftover '('
}

Longest valid substring needs indices, not characters, because the answer is a length:

int longestValid(const string& s) {
    vector<int> st{-1};          // sentinel: index before the string
    int best = 0;
    for (int i = 0; i < (int)s.size(); ++i) {
        if (s[i] == '(') st.push_back(i);
        else {
            st.pop_back();
            if (st.empty()) st.push_back(i);        // new boundary
            else best = max(best, i - st.back());
        }
    }
    return best;
}

The sentinel -1 and the “push the index back when the stack empties” step are what make the length arithmetic work. Without them, ()() reports 2 instead of 4.

QQuestionIn longestValid, what does the index on the stack represent?
ASolution

The position just before the current run of valid parentheses. The length of the run ending at i is i - that index.

Stack permutations and Catalan numbers

Take input 1, 2, ..., n and a stack. Push in order, pop whenever you like. Which output permutations are reachable?

The greedy check is exact: for each wanted value, push until it is on top, then pop it. If you run out of input before finding it, the permutation is impossible.

bool validStackPermutation(const vector<int>& target) {
    vector<int> st;
    int next = 1, n = (int)target.size();
    for (int x : target) {
        while (st.empty() || st.back() != x) {
            if (next > n) return false;      // needed value is buried
            st.push_back(next++);
        }
        st.pop_back();
    }
    return true;
}

For n = 3, 3 1 2 fails: push 1, 2, 3, pop 3, and now 2 sits on top of 1, so 1 cannot come next. 2 3 1 works: push 1, 2, pop 2, push 3, pop 3, pop 1.

The number of valid permutations is the \(n\)-th Catalan number:

\[ C_n = \frac{1}{n+1}\binom{2n}{n}, \qquad C_0 = 1,\quad C_n = \sum_{i=0}^{n-1} C_i C_{n-1-i} \]

\(n\) 0 1 2 3 4 5 6 7 8
\(C_n\) 1 1 2 5 14 42 132 429 1430
unsigned long long catalan(int n) {          // C_20 = 6.5e9 needs 64 bits
    vector<unsigned long long> c(n + 1, 0);
    c[0] = 1;
    for (int i = 1; i <= n; ++i)
        for (int j = 0; j < i; ++j)
            c[i] += c[j] * c[i - 1 - j];
    return c[n];
}

The recurrence is the “split at the first element” argument: pick when the first pushed element is popped; everything before it and everything after it are independent subproblems of the same kind. The same numbers count balanced parenthesis strings with \(n\) pairs, binary trees with \(n\) nodes, and monotonic lattice paths that stay above the diagonal.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  g/.style={draw, black!25}]
  \draw[step=1, g] (0,0) grid (3,3);
  \draw[very thick, orange] (0,0) -- (0,1) -- (0,2) -- (1,2) -- (2,2) -- (2,3) -- (3,3);
  \draw[very thick, blue!45, dashed] (0,0) -- (3,3);
  \node[font=\scriptsize, anchor=north] at (1.5,-0.15) {paths that never cross y=x: C3 = 5};
  \fill[green!55] (0,1) circle (2pt); \fill[green!55] (2,3) circle (2pt);
\end{tikzpicture}

Two traps: the numbers grow fast, so int overflows at \(C_{17}\); and the check must compare the top before pushing, otherwise a value already in the stack gets pushed again and the answer is wrong in the permissive direction.

QQuestionWhy does the greedy “push until the wanted value is on top” check

decide the problem?

ASolution

The output order forces the pops: to emit x, everything before it must already be pushed, and x must be on top with nothing larger above it. That leaves no choice, so if the forced moves fail, no sequence works.

Bugs and edge cases

QQuestionYour sliding-window maximum is correct on the samples but fails on

k = n. What is the likely bug?

ASolution

Usually the expiry check or the output guard: dq.front() <= i - k should use <=, and output should start at i >= k - 1. With k = n only one window exists, so an off-by-one there is visible immediately.

Next: Hashing and Hash Tables (DSA Core #4) — why average \(O(1)\) is not a promise, and how to build an LRU cache from a map plus a list.