"""Stack (last in, first out) and a classic use: balanced brackets.

Idea
----
A stack only touches its top: ``push`` adds there, ``pop`` removes from
there. A Python list already behaves like this when you use ``append`` and
``pop()`` at the end, both amortised O(1). The wrapper below just names the
operations and gives clear errors.

Complexity
----------
push / pop / peek: O(1) amortised
Space: O(n)
"""

from typing import Generic, TypeVar

T = TypeVar("T")


class Stack(Generic[T]):
    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        if not self._items:
            raise IndexError("pop from empty stack")
        return self._items.pop()

    def peek(self) -> T:
        if not self._items:
            raise IndexError("peek at empty stack")
        return self._items[-1]

    def __len__(self) -> int:
        return len(self._items)

    def __bool__(self) -> bool:
        return bool(self._items)


def is_balanced(text: str) -> bool:
    """Return True if every bracket in ``text`` is closed in the right order."""
    pairs = {")": "(", "]": "[", "}": "{"}
    stack: Stack[str] = Stack()
    for ch in text:
        if ch in "([{":
            stack.push(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack
