Check Balanced Delimiter Nesting

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a string s made up exclusively of the six delimiter characters '(', ')', '[', ']', '{', and '}', return True if s is properly balanced and nested, or False otherwise:

def is_valid(s: str) -> bool:

A delimiter string is well-formed when all three conditions hold simultaneously:

  1. Matching pairs: '(' pairs only with ')', '[' pairs only with ']', and '{' pairs only with '}'.
  2. Last-opened, first-closed order: whenever one delimiter is opened inside another, the inner delimiter must close before the outer delimiter closes.
  3. Complete pairing: every closing character matches a preceding unclosed opening character, and no opening character remains unclosed at the end of s (an empty string "" has zero unmatched characters and evaluates to True).

Examples

Example 1

Input: s = "[()]{}"
Output: True

'(' opens inside '[' and closes first with ')', then ']' closes '[', followed by '{' closing with '}'. Every delimiter matches both in symbol type and in nesting order.

Example 2

Input: s = "{[}]"
Output: False

'[' is opened after '{', so ']' is required before '}' may appear. Seeing '}' while '[' is still open violates nesting order.

Example 3

Input: s = "([]){"
Output: False

Although the prefix "([])" balances cleanly, the trailing '{' never receives a matching '}' before the string ends.

Constraints

  • 0 <= len(s) <= 10^4
  • Every character in s is one of '(', ')', '[', ']', '{', or '}'

Step-by-step walkthrough

  1. Understand the goal and rules

    We are given a string s of up to 10,000 characters drawn only from (, ), [, ], {, and }. We want to return True if every bracket pair is properly nested and matched, and False otherwise.

    Three conditions must hold at the same time:

    • Same type: ( only pairs with ), [ only with ], and { only with }.
    • Innermost closes first: if we open { and then open [ inside it, [ must be closed by ] before { can be closed by }. Crossing pairs like "{[}]" are invalid.
    • Nothing left unmatched: no closing bracket may appear before a matching opener (")" is invalid), and no opening bracket may remain unclosed at the end ("([]){" is invalid). An empty string "" has zero unmatched brackets, so it is valid.
  2. Why simple counting fails (and why string deletion is slow)

    A tempting first try is to keep three counters — one for (), one for [], and one for {} — adding 1 on an opener, subtracting 1 on a closer, checking that no counter drops below 0, and checking that all three end at 0.

    Counters catch "((" and ")(", but they fail on "{[}]": both {} and [] stay non-negative and end at 0, yet the two pairs cross each other. Separate counters remember how many brackets of each type are open, but forget the order in which they were opened.

    Another idea is to repeatedly delete adjacent "()", "[]", and "{}" substrings until nothing changes, then check whether the string is empty. That respects nesting order, so it is a great reference check for tests, but on a deeply nested string like ((...)) of length n it makes n / 2 passes and copies the string each pass, taking O(n²) time. We can validate the string in a single O(n) left-to-right pass instead.

  3. Key idea: track open brackets on a stack

    Think of opening a bracket like opening a nested box: if you open a { box and put an open [ box inside it, you must close the inner [ box before you can close the outer { box. The bracket that must close next is always the most recently opened bracket that is still open.

    A stack — a last-in, first-out (LIFO) list where we only add (append) and remove (pop) items at the top end — models this rule directly:

    • When we see an opening bracket, we push it onto the top of open_stack.
    • When we see a closing bracket, we look at the top of open_stack:
      • If open_stack is empty, there is nothing open to close -> return False.
      • If the top bracket is the wrong type, the pairs cross -> return False.
      • Otherwise they match, so we pop that top opener off the stack and keep going.
    • After scanning the whole string, we return True if and only if open_stack is completely empty.

    Watch open_stack on Example 1 ("[()]{}", valid) versus Example 2 ("{[}]", crossed):

    Trace 1: s = "[()]{}"
      read '['  (opener) -> push '['            open_stack = ['[']
      read '('  (opener) -> push '('            open_stack = ['[', '(']   <-- top is '('
      read ')'  (closer) -> needs '(', matches! open_stack = ['[']        (popped '(')
      read ']'  (closer) -> needs '[', matches! open_stack = []           (popped '[')
      read '{'  (opener) -> push '{'            open_stack = ['{']
      read '}'  (closer) -> needs '{', matches! open_stack = []           (popped '{')
      end of s           -> open_stack is empty -> True
    
    Trace 2: s = "{[}]"
      read '{'  (opener) -> push '{'            open_stack = ['{']
      read '['  (opener) -> push '['            open_stack = ['{', '[']   <-- top is '['
      read '}'  (closer) -> needs '{', but top is '[' -> mismatch! -> False immediately
    
  4. Map each closer to its required opener

    When a closing bracket like ']' arrives, the question we ask is: "What opening bracket must be sitting at the top of open_stack right now?"

    Storing a dictionary matching_opener with closing brackets as keys and opening brackets as values answers both questions we have about any character ch in O(1) time:

    1. ch in matching_opener tells us whether ch is a closing bracket (since s contains only the six bracket characters, anything else is an opening bracket).
    2. matching_opener[ch] tells us the exact opening partner required on top of the stack.
    matching_opener = {
        ")": "(",
        "]": "[",
        "}": "{",
    }
    
  5. Write the left-to-right scan

    Now we combine matching_opener and open_stack inside a single loop over s. Notice two boundary checks that prevent subtle bugs:

    1. Check not open_stack before open_stack[-1]: Python's or short-circuits from left to right. If s starts with ")", open_stack is empty, so not open_stack is True and Python returns False immediately without ever evaluating open_stack[-1] (which would crash with IndexError).
    2. Return len(open_stack) == 0 at the end: Simply returning True after the loop would mistakenly accept "(((", where no mismatch occurs during the loop because no closing bracket ever arrives.
    from typing import Dict, List
    
    
    def is_valid(s: str) -> bool:
        matching_opener: Dict[str, str] = {
            ")": "(",
            "]": "[",
            "}": "{",
        }
        open_stack: List[str] = []
    
        for ch in s:
            if ch in matching_opener:
                expected_opener = matching_opener[ch]
                if not open_stack or open_stack[-1] != expected_opener:
                    return False
                open_stack.pop()
            else:
                open_stack.append(ch)
    
        return len(open_stack) == 0
    
  6. Complete solution

    Here is the complete solution with all imports and explanatory comments ready to run:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def is_valid(s: str) -> bool:
        # Map each closing bracket to the exact opening bracket that must sit on top of the stack.
        matching_opener: Dict[str, str] = {
            ")": "(",
            "]": "[",
            "}": "{",
        }
        # open_stack: LIFO list of unclosed opening brackets in the order seen, e.g. ['{', '['].
        open_stack: List[str] = []
    
        for ch in s:
            if ch in matching_opener:
                # Closing-bracket phase: it must close the most recently opened bracket.
                # Check `not open_stack` first so a stray closer like ")" never indexes an empty list.
                expected_opener = matching_opener[ch]
                if not open_stack or open_stack[-1] != expected_opener:
                    return False
                open_stack.pop()
            else:
                # Opening-bracket phase: record this opener on top of the stack until its closer arrives.
                open_stack.append(ch)
    
        # Valid only when every opening bracket was matched and popped (catches inputs like "((").
        return len(open_stack) == 0
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine opening and closing nested cardboard boxes: if you open a large { box and place an open [ box inside it, you cannot tape the outer { box shut until you first close the inner [ box. The bracket that must be closed next is always the most recently opened one that is still waiting for its partner. We track those waiting openers on a stack — a last-in, first-out (LIFO) list where items are only added and removed at one end, called the top.

A naive approach of keeping three separate integer counters (one for (), one for [], and one for {}) fails on crossed inputs like "{[}]", because each type's count stays non-negative and ends at zero even though the pairs overlap illegally. Another obvious approach — repeatedly calling s.replace("()", "") and similar replacements until the string stops shrinking — gets the right answer, but copies the string on every layer of nesting and takes O(n²) time in the worst case. Using a stack lets us verify both type and nesting order in a single left-to-right pass.

Here is how the stack handles Example 1 ("[()]{}") versus Example 2 ("{[}]"):

  • On "[()]{}": push '[' (['[']), push '(' (['[', '(']), match ')' and pop '(' (['[']), match ']' and pop '[' ([]), push '{' (['{']), match '}' and pop '{' ([]). The stack ends empty, returning True.
  • On "{[}]": push '{' (['{']), push '[' (['{', '[']), see '}' which requires '{', while the stack's top item is '['. We return False right away.

Complexity

  • Time: O(n), where n is the length of s. We visit each character at most once, and each dictionary lookup (ch in matching_opener), list append (open_stack.append), and list pop (open_stack.pop) takes O(1) time.
  • Space: O(n) in the worst case. When s consists purely of opening brackets (such as "(((("), all n characters sit on open_stack at once; the matching_opener dictionary uses O(1) space because it stores only 3 fixed key-value pairs.

Edge cases

  • Empty string (""): The loop runs zero iterations and len(open_stack) == 0 returns True, since there are no unmatched brackets.
  • Odd-length strings ("(()", "["): Every valid bracket pair uses 2 characters, so an odd-length string can never be valid. The stack handles this automatically (either a closer finds no match or at least one opener remains on open_stack at the end); adding if len(s) % 2 != 0: return False at the top is an optional O(1) shortcut.
  • Only opening brackets ("(({["): No mismatch happens inside the loop, so the final len(open_stack) == 0 check is what catches the unclosed openers and returns False.
  • Closing bracket first (")", ")("): open_stack is empty on the very first character, and checking not open_stack before open_stack[-1] safely returns False without raising IndexError.
  • Deep nesting at max length (10^4 characters): 5,000 nested pairs push 5,000 elements onto open_stack, which a Python list handles effortlessly, whereas a recursive parser with one call per nesting level would hit Python's default recursion limit of 1,000.

Common mistakes

  • Counting bracket types instead of stacking them: Keeping counters for (), [], and {} accepts crossed strings like "{[}]" because counters discard the order in which brackets were opened.
  • Indexing open_stack[-1] or calling pop() before checking if the stack is empty: Any input starting with a closing bracket (like "]") crashes with IndexError: list index out of range.
  • Returning True unconditionally after the loop: Forgetting return len(open_stack) == 0 causes inputs with leftover opening brackets like "((" to falsely pass.
  • Keying the dictionary by opening brackets instead of closing brackets: Mapping "(" -> ")" works if you push the expected closer onto the stack, or if you check opener_to_closer[open_stack[-1]] == ch, but beginners often mix up how to test whether ch itself is an opener or closer. Keying by closing brackets (")": "(") lets ch in matching_opener do both jobs cleanly.

Follow-up questions

  • How can you generalize the validator when caller-defined opener/closer pairs are supplied at runtime? Pass matching_opener (mapping each closer to its opener) as an argument and build openers = set(matching_opener.values()) once in O(t) time for t bracket types. During the scan, push ch if ch in openers, validate and pop if ch in matching_opener, and ignore any non-bracket characters if text is allowed; total time stays O(n) and space becomes O(n + t). If symmetric delimiters whose opener and closer are identical (such as "|" or '"') are allowed, handle them by popping when the same symbol is already at open_stack[-1] and pushing otherwise.

    python def is_valid_custom(s: str, matching_opener: dict[str, str]) -> bool: openers = set(matching_opener.values()) open_stack: list[str] = [] for ch in s: if ch in matching_opener: if not open_stack or open_stack[-1] != matching_opener[ch]: return False open_stack.pop() elif ch in openers: open_stack.append(ch) return len(open_stack) == 0

  • What are the asymptotic time and memory bounds, and how can auxiliary memory become O(1) when only parentheses '(' and ')' appear? The general stack solution runs in O(n) time and O(n) worst-case space. When the string contains only one bracket type (say '(' and ')'), every item on the stack would be identical ('('), so the stack's contents carry no extra information beyond its length. We can replace the list with a single integer open_count: add 1 for '(', subtract 1 for ')', return False immediately if open_count < 0, and check open_count == 0 at the end — keeping O(n) time while shrinking auxiliary space to O(1).

    python def is_valid_single_type(s: str) -> bool: open_count = 0 for ch in s: if ch == "(": open_count += 1 else: open_count -= 1 if open_count < 0: return False return open_count == 0

  • How would you change the scan to report the character index of the earliest nesting error rather than True or False? Push integer indices onto open_stack instead of characters (open_stack.append(i)), since s[open_stack[-1]] still tells us which opening bracket sits on top. Whenever a closing bracket at index i sees an empty stack or mismatches s[open_stack[-1]], index i is the first invalid position as we read left to right, so return i immediately. If the loop finishes with unclosed brackets still on open_stack, clarify the convention with the interviewer: returning open_stack[0] reports the earliest unclosed opener (while open_stack[-1] reports the innermost unclosed opener), and returning -1 signals a completely valid string.

    python def first_mismatch_index(s: str) -> int: matching_opener = {")": "(", "]": "[", "}": "{"} open_stack: list[int] = [] # indices of unclosed opening brackets for i, ch in enumerate(s): if ch in matching_opener: if not open_stack or s[open_stack[-1]] != matching_opener[ch]: return i open_stack.pop() else: open_stack.append(i) return open_stack[0] if open_stack else -1

Follow-up questions

Similar questions

More Bloomberg interview questions

All 47 Bloomberg questions →