Skip to content
    Algoria

    STACKS & QUEUES · 7 MIN

    Stacks

    A stack is Last-In-First-Out: push to the top, pop from the top.

    BYTE explains

    • push and pop are O(1).
    • Used for undo, browser back, function calls and matching brackets.
    • In Python a list works: append() is push, pop() is pop.

    Real world: A stack of plates — you take the one you put down last.

    Watch it move

    Empty stack

    1/8

    Code

    def balanced(s):
        pairs = {')': '(', ']': '[', '}': '{'}
        st = []
        for ch in s:
            if ch in '([{': st.append(ch)
            elif ch in pairs:
                if not st or st.pop() != pairs[ch]: return False
        return not st
    Try it in the online compiler →

    Checkpoint quiz

    Push 1, 2, 3 then pop once. What is on top?