Stacks · Easy

Valid parentheses

Input contains only ()[]{}. Return whether the brackets are balanced and correctly nested. Every closer must match the most recent opener that is still unmatched.

Worked example

'([])' → True

  1. Record ( and then [ as unmatched openers.
  2. ] matches [, then ) matches (. Nothing remains unmatched, so return True.

Python solution

def solve(brackets):
    stack = []
    pairs = {')': '(', ']': '[', '}': '{'}
    for char in brackets:
        if char not in pairs:
            stack.append(char)
        elif not stack or stack.pop() != pairs[char]:
            return False
    return not stack

The most recently opened bracket must be the first one closed.

Time: O(n) · Space: O(n)

Practise in GymType