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:
- Matching pairs:
'('pairs only with')','['pairs only with']', and'{'pairs only with'}'. - Last-opened, first-closed order: whenever one delimiter is opened inside another, the inner delimiter must close before the outer delimiter closes.
- 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 toTrue).
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
sis one of'(',')','[',']','{', or'}'
Step-by-step walkthrough
Understand the goal and rules
We are given a string
sof up to 10,000 characters drawn only from(,),[,],{, and}. We want to returnTrueif every bracket pair is properly nested and matched, andFalseotherwise.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.
- Same type:
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{}— adding1on an opener, subtracting1on a closer, checking that no counter drops below0, and checking that all three end at0.Counters catch
"(("and")(", but they fail on"{[}]": both{}and[]stay non-negative and end at0, 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 lengthnit makesn / 2passes and copies the string each pass, takingO(n²)time. We can validate the string in a singleO(n)left-to-right pass instead.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_stackis empty, there is nothing open to close -> returnFalse. - If the top bracket is the wrong type, the pairs cross -> return
False. - Otherwise they match, so we
popthat top opener off the stack and keep going.
- If
- After scanning the whole string, we return
Trueif and only ifopen_stackis completely empty.
Watch
open_stackon 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- When we see an opening bracket, we push it onto the top of
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 ofopen_stackright now?"Storing a dictionary
matching_openerwith closing brackets as keys and opening brackets as values answers both questions we have about any characterchinO(1)time:ch in matching_openertells us whetherchis a closing bracket (sincescontains only the six bracket characters, anything else is an opening bracket).matching_opener[ch]tells us the exact opening partner required on top of the stack.
matching_opener = { ")": "(", "]": "[", "}": "{", }Write the left-to-right scan
Now we combine
matching_openerandopen_stackinside a single loop overs. Notice two boundary checks that prevent subtle bugs:- Check
not open_stackbeforeopen_stack[-1]: Python'sorshort-circuits from left to right. Ifsstarts with")",open_stackis empty, sonot open_stackisTrueand Python returnsFalseimmediately without ever evaluatingopen_stack[-1](which would crash withIndexError). - Return
len(open_stack) == 0at the end: Simply returningTrueafter 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- Check
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, returningTrue. - On
"{[}]": push'{'(['{']), push'['(['{', '[']), see'}'which requires'{', while the stack's top item is'['. We returnFalseright away.
Complexity
- Time:
O(n), wherenis the length ofs. 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) takesO(1)time. - Space:
O(n)in the worst case. Whensconsists purely of opening brackets (such as"(((("), allncharacters sit onopen_stackat once; thematching_openerdictionary usesO(1)space because it stores only 3 fixed key-value pairs.
Edge cases
- Empty string (
""): The loop runs zero iterations andlen(open_stack) == 0returnsTrue, 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 onopen_stackat the end); addingif len(s) % 2 != 0: return Falseat the top is an optionalO(1)shortcut. - Only opening brackets (
"(({["): No mismatch happens inside the loop, so the finallen(open_stack) == 0check is what catches the unclosed openers and returnsFalse. - Closing bracket first (
")",")("):open_stackis empty on the very first character, and checkingnot open_stackbeforeopen_stack[-1]safely returnsFalsewithout raisingIndexError. - Deep nesting at max length (
10^4characters): 5,000 nested pairs push 5,000 elements ontoopen_stack, which a Python list handles effortlessly, whereas a recursive parser with one call per nesting level would hit Python's default recursion limit of1,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 callingpop()before checking if the stack is empty: Any input starting with a closing bracket (like"]") crashes withIndexError: list index out of range. - Returning
Trueunconditionally after the loop: Forgettingreturn len(open_stack) == 0causes 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 checkopener_to_closer[open_stack[-1]] == ch, but beginners often mix up how to test whetherchitself is an opener or closer. Keying by closing brackets (")": "(") letsch in matching_openerdo 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 buildopeners = set(matching_opener.values())once inO(t)time fortbracket types. During the scan, pushchifch in openers, validate and pop ifch in matching_opener, and ignore any non-bracket characters if text is allowed; total time staysO(n)and space becomesO(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 atopen_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 andO(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 integeropen_count: add1for'(', subtract1for')', returnFalseimmediately ifopen_count < 0, and checkopen_count == 0at the end — keepingO(n)time while shrinking auxiliary space toO(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_stackinstead of characters (open_stack.append(i)), sinces[open_stack[-1]]still tells us which opening bracket sits on top. Whenever a closing bracket at indexisees an empty stack or mismatchess[open_stack[-1]], indexiis the first invalid position as we read left to right, so returniimmediately. If the loop finishes with unclosed brackets still onopen_stack, clarify the convention with the interviewer: returningopen_stack[0]reports the earliest unclosed opener (whileopen_stack[-1]reports the innermost unclosed opener), and returning-1signals 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
- How can you generalize the validator when caller-defined opener/closer pairs are supplied at runtime?
- What are the asymptotic time and memory bounds, and how can auxiliary memory become O(1) when only parentheses '(' and ')' appear?
- How would you change the scan to report the character index of the earliest nesting error rather than True or False?
Similar questions
- Sum Forward-Order Digit Lists
- Equalize Letter Counts by One Deletion
- Minimum Conference Rooms and Postfix Evaluator
- Directed Friend Requests Under Age Bounds
- Island Area Frequency Queries
- Dynamic Multiset Top-K Frequency Tracker
More Bloomberg interview questions
- Count Islands in a Grid Medium
- Column-Order Binary Tree Traversal Medium
- Minimum Substitutions to Form an Anagram Medium Pro
- Enumerate Binary Strings From Wildcard Pattern Medium Pro
- Complete Concrete Subclasses in an Abstract Command Hierarchy Medium Pro
- Parse Clickstream URLs and Tracking Parameters in PostgreSQL Medium Pro
- Software Project Reflection and Technical Leadership Prompts Medium Pro
- Directed Friend Requests Under Age Bounds Medium Pro
- Leading Full-Cycle Client Software Delivery Hard Pro
- Low-Latency Streaming VWAP Market Data Engine Medium Pro