Stacks: Last In, First Out

A pile of plates

A stack only lets you touch the top. The last thing in is the first thing out: LIFO.

Think of it like this: A stack of plates. Your browser's Back button and an editor's Undo work the same way.

Operationstd::stackBig-O
push on tops.push(x)O(1)
remove tops.pop()O(1)
look at tops.top()O(1)
is it empty?s.empty()O(1)
#include <iostream>
#include <stack>
#include <string>
using namespace std;

bool balanced(const string& text) {
    stack<char> s;
    for (char ch : text) {
        if (ch == '(' || ch == '[' || ch == '{') s.push(ch);
        else if (ch == ')' || ch == ']' || ch == '}') {
            char want = ch == ')' ? '(' : ch == ']' ? '[' : '{';
            if (s.empty() || s.top() != want) return false;
            s.pop();
        }
    }
    return s.empty();
}

int main() {
    for (string t : {"{[()()]}", "([)]", "((", "f(a[0])"})
        cout << t << " " << (balanced(t) ? "balanced" : "not balanced") << endl;
    return 0;
}

Output

{[()()]} balanced
([)] not balanced
(( not balanced
f(a[0]) balanced

Common mistake: s.pop() returns nothing in C++ – read s.top() first. And never call top() or pop() on an empty stack: it's undefined behaviour (often a crash).

HOME LABS COMMUNITY DASHBOARD