Lecture 4: Exam prep

What this page is

The exam has three problem-solving questions, probably one each on linked lists, stacks and queues. This page collects the classic stack problems (many are LeetCode staples) that reuse the ideas from Lecture 4 - Stack. It is extra practice, not from the slides.

Which stack to use in your answer

The solutions below use std::stack from <stack> to keep them short. It maps directly onto the course ADT:

Course ADT (Stackt / StackL) std::stack<T> s
push(el) s.push(el)
pop(el) (read and remove) el = s.top(); s.pop(); (pop() returns nothing)
stackTop(el) el = s.top();
stackIsEmpty() s.empty()
s.top() and s.pop() on an empty std::stack

Both are undefined behaviour, not an error message. Always test s.empty() first. If the exam says “use the stack class from the lecture”, swap in push, pop(x), stackTop(x) and stackIsEmpty(); the logic doesn’t change.

Problem patterns

Problem Core idea Time / extra space
Reverse a string or sequence push all, pop all O(n) / O(n)
Balanced brackets push openers, a closer must match the top O(n) / O(n)
Evaluate postfix operands on the stack; operator pops right then left O(n) / O(n)
Valid pop sequence simulate: push in order, pop while the top matches O(n) / O(n)
Min stack second stack of minimums O(1) per op / O(n)
Next greater element monotonic stack of waiting indices O(n) / O(n)
Remove adjacent duplicates the result string is the stack O(n) / O(n)
Sort a stack second stack kept sorted O(n²) / O(n)
Print a linked list backwards push every node, then pop O(n) / O(n)
Queue from two stacks in stack, out stack, pour when out is empty O(1) amortized / O(n)
When to reach for a stack

If the problem says “most recent”, “matching”, “undo”, “reverse”, “nearest to the left/right” or “nested”, the answer is almost always a stack. The thing you need next is the thing you saw last.

Reverse a string

std::string reverseStr(const std::string& s) {
    std::stack<char> st;
    for (char c : s) st.push(c);
    std::string out;
    while (!st.empty()) {
        out += st.top();
        st.pop();
    }
    return out;
}

"stack" becomes "kcats". The same pattern reverses an array, the words of a sentence (push words, not characters), or the digits of a base conversion.

Balanced brackets (LeetCode 20)

bool isValid(const std::string& s) {
    std::stack<char> st;
    for (char c : s) {
        if (c == '(' || c == '[' || c == '{') {
            st.push(c);
        } else if (c == ')' || c == ']' || c == '}') {
            if (st.empty()) return false;              // nothing to close
            char open = st.top();
            st.pop();
            if ((c == ')' && open != '(') ||
                (c == ']' && open != '[') ||
                (c == '}' && open != '{')) return false; // wrong kind
        }
    }
    return st.empty();                                 // leftovers = unclosed
}

"{[()]}" → true, "{[(])}" → false at the ], "((" → false at the end, "())" → false at the last ).

Evaluate postfix (LeetCode 150)

int evalRPN(const std::vector<std::string>& tokens) {
    std::stack<int> st;
    for (const std::string& t : tokens) {
        if (t == "+" || t == "-" || t == "*" || t == "/") {
            int right = st.top(); st.pop();   // first pop = right
            int left  = st.top(); st.pop();   // second pop = left
            if      (t == "+") st.push(left + right);
            else if (t == "-") st.push(left - right);
            else if (t == "*") st.push(left * right);
            else               st.push(left / right);
        } else {
            st.push(std::stoi(t));            // handles "-3" too
        }
    }
    return st.top();
}

2 1 + 3 * → 9. 4 13 5 / + → 4 + 13/5 = 4 + 2 → 6. Swapping left and right gives 5 / 13 = 0 and the wrong answer, which is the classic mistake.

Valid pop sequence (LeetCode 946)

“Values 1 to n are pushed in order, with pops in between. Can the output be this sequence?” Simulate it: push the next value, then pop for as long as the top is the next expected output.

bool validSequence(const std::vector<int>& pushed, const std::vector<int>& popped) {
    std::stack<int> st;
    size_t j = 0;                               // next value we expect to pop
    for (int x : pushed) {
        st.push(x);
        while (!st.empty() && j < popped.size() && st.top() == popped[j]) {
            st.pop();
            ++j;
        }
    }
    return st.empty();                          // everything popped in order
}

Pushing 1 2 3 4 5:

  • 4 5 3 2 1 is possible: push 1–4, pop 4, push 5, pop 5, then pop 3, 2, 1.
  • 4 3 5 1 2 is impossible: after popping 4, 3, 5 the stack holds 1 2 with 2 on top, so 1 can’t come out before 2.
The quick mental check

Once a value x is popped, every smaller value still on the stack must come out in decreasing order. If a later pop wants a smaller value that’s buried under another one, the sequence is impossible.

Min stack (LeetCode 155)

Support push, pop, top and getMin, all O(1).

class MinStack {
    std::stack<int> vals;
    std::stack<int> mins;   // top is always the current minimum
public:
    void push(int x) {
        vals.push(x);
        if (mins.empty() || x <= mins.top())   // <= keeps duplicates
            mins.push(x);
    }
    void pop() {
        if (vals.top() == mins.top()) mins.pop();
        vals.pop();
    }
    int top() const    { return vals.top(); }
    int getMin() const { return mins.top(); }
};

Push 5, 3, 7, 3: vals = 5 3 7 3, mins = 5 3 3, getMin() = 3. Pop (the 3): mins = 5 3, min still 3. Pop (7): min 3. Pop (3): mins = 5, min 5. With < instead of <=, the second 3 is never added to mins, so popping it would remove the only 3 from mins and getMin() would wrongly report 5 while a 3 is still in the stack.

Next greater element (monotonic stack)

For each element, find the first larger element to its right (or −1). The stack holds indices still waiting for an answer; their values are decreasing from bottom to top.

std::vector<int> nextGreater(const std::vector<int>& a) {
    std::vector<int> ans(a.size(), -1);
    std::stack<int> st;                           // indices waiting for a greater value
    for (int i = 0; i < (int)a.size(); ++i) {
        while (!st.empty() && a[st.top()] < a[i]) {
            ans[st.top()] = a[i];                 // a[i] answers them
            st.pop();
        }
        st.push(i);
    }
    return ans;                                   // anything left stays -1
}
i a[i] pops (answered) stack after (indices)
0 2 0
1 1 0 1
2 5 1 → 5, 0 → 5 2
3 3 2 3
4 6 3 → 6, 2 → 6 4

[2, 1, 5, 3, 6] → [5, 5, 6, 6, -1]. Each index is pushed once and popped at most once, so it’s O(n) even with the inner loop. “Daily temperatures” (LeetCode 739) is the same code storing i - st.top() instead of a[i].

Remove adjacent duplicates (LeetCode 1047)

std::string removeDuplicates(const std::string& s) {
    std::string st;                 // a string used as a stack
    for (char c : s) {
        if (!st.empty() && st.back() == c) st.pop_back();   // pair cancels
        else                               st.push_back(c);
    }
    return st;
}

"abbaca": a → ab → a → (empty) → c → ca. Result "ca". Removing bb makes the two as adjacent, and the stack handles that automatically.

Sort a stack using a second stack

std::stack<int> sortStack(std::stack<int> in) {
    std::stack<int> out;                     // sorted, largest on top
    while (!in.empty()) {
        int x = in.top(); in.pop();
        while (!out.empty() && out.top() > x) {
            in.push(out.top());              // move bigger ones back
            out.pop();
        }
        out.push(x);                         // x is now in its place
    }
    return out;
}

Like insertion sort: each value waits in x while larger values move back to in, then slots in. O(n²) in the worst case.

struct Node { int val; Node* next; };

void printReverse(Node* head) {
    std::stack<int> st;
    for (Node* p = head; p; p = p->next) st.push(p->val);
    while (!st.empty()) {
        std::cout << st.top() << ' ';
        st.pop();
    }
}

1 → 2 → 3 prints 3 2 1 without changing the list. A recursive version (print the rest, then this node) does the same thing with the system stack.

Queue from two stacks (LeetCode 232)

A preview of Lecture 5 - Queue: two LIFOs make a FIFO.

class MyQueue {
    std::stack<int> in, out;
    void pour() {                            // only when out is empty
        if (out.empty())
            while (!in.empty()) { out.push(in.top()); in.pop(); }
    }
public:
    void push(int x) { in.push(x); }
    int pop()        { pour(); int x = out.top(); out.pop(); return x; }
    int front()      { pour(); return out.top(); }
    bool empty() const { return in.empty() && out.empty(); }
};

Pouring reverses in, so the oldest element ends up on top of out. Each element is moved at most once, so the operations are O(1) amortized.

Only pour into an empty out

If you pour while out still has elements, newer elements land on top of older ones and come out first, which breaks FIFO order.

How to trace these in the exam

Draw the stack as a vertical column (or write it bottom → top in brackets), and redraw it after every token or operation. Write down each popped value next to the step. Then check the edge cases: empty input, popping from an empty stack, and what’s left on the stack at the end.


Cheat sheet

  • std::stack: push, top (read), pop (remove, returns nothing), empty. Check empty() before top/pop.
  • Brackets: push openers; closer needs a non-empty stack and a matching top; must end empty.
  • Postfix: first pop is the right operand.
  • Valid pop sequence: simulate pushes, pop while the top matches; valid if the stack ends empty.
  • Min stack: second stack, push when x <= min, pop when equal.
  • Next greater: keep waiting indices; a bigger value pops and answers them. O(n).
  • Adjacent duplicates: matching top cancels; the stack is the answer.
  • Queue from stacks: push to in; pour into out only when out is empty.