Bracket Matching

Problem:
https://open.kattis.com/problems/bracketmatching

This problem asks you to determine whether a string of brackets is valid.
A string is valid if:

This is a classic stack problem.


💡 Approach

We use:

Time complexity: O(n)
Space complexity: O(n) (worst case, all openings)


# 2.1 Bracket Matching
# stack-based validation

import sys
sys.stdin = open('test.txt', 'r')

n = int(sys.stdin.readline())
# without strip, '\n' is treated as a character
s = sys.stdin.readline().strip()

# list of open brackets
o = ['(', '[', '{']

# dictionary mapping open to close brackets
d = {
    '(': ')',
    '[': ']',
    '{': '}'
}

# stack for open brackets
stack = []
v = 'Valid'

for c in s:
    # if open bracket, push to stack
    if c in o:
        stack.append(c)
    else:
        # if closing bracket, ensure stack is not empty
        if stack:
            x = stack.pop()
            # mismatch?
            if d[x] != c:
                v = 'Invalid'
                break
        else:
            v = 'Invalid'
            break

# leftover opening brackets = invalid
if stack:
    v = 'Invalid'

print(v)