Algorithmsstack matching

Stack Matching — Nested and Paired Symbols

TT
Testlaa Team
May 14, 20261 min read

Every opener expects a matching closer in order. A stack stores “what is still waiting to be closed.”

Try this in Python

def valid(s: str) -> bool:
    st: list[str] = []
    pairs = {")": "(", "}": "{", "]": "["}
    for ch in s:
        if ch in "({[":
            st.append(ch)
        elif ch in pairs:
            if not st or st.pop() != pairs[ch]:
                return False
        else:
            return False
    return not st


print(valid("([])"), valid("([)]"))

Key takeaways

  • Mismatch on pop → invalid.
  • Non-bracket characters need their own rules in real parsers.
  • Same skeleton works for XML/HTML-style nesting with tags.

Tags:

Stacks & queuesPythonStudents