Balanced brackets
Check whether the round, square and curly brackets in a code fragment are properly nested. The textbook use of a stack.
A code editor highlights an error when brackets go out of sync. We need a function that tells whether the brackets (), [] and {} in code are balanced: every opening bracket has a closing one of the same kind and pairs do not interleave (([)] is wrong). All other characters are ignored.
Task
Return true when the brackets are correct, otherwise false. An empty string (or one without brackets) is correct.
Signatures: isBalanced(code) (JS/TS), is_balanced(code) (Python), Solution.IsBalanced (C#), Solution.isBalanced (Java), IsBalanced (Go).
Examples
code | Result |
|---|---|
"([{}])" | true |
"function f(a) { return [a]; }" | true |
"([)]" | false – pairs interleave |
"())(" | false – closing without opening |
"((" | false – something is left open |
Constraints
0 ≤ code.length ≤ 200,000, ASCII characters.- Nesting can be 100,000 levels deep – recursion is not a good idea.
Expected complexity
O(n) time, O(n) memory in the worst case (only opening brackets).