Balanced brackets
easy
New here? How this page works
- Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
- Open Break it down. Answer the questions in your own words. This is your plan.
- Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
- Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
- Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
- Press Submit. It runs hidden tests too. Pass them all, and it's solved.
text is made of the brackets (, ), [, ], { and }. It's balanced when every opening bracket is closed by the same kind of bracket, and brackets close in the right order: the most recently opened one first.
So {[()()]} is balanced, but {[(])} is not: the ] arrives while the ( is still open.
Return true if text is balanced, and false if not.
Examples
Example 1
- Input
- text = "{[()()]}"
- Output
- true
Each bracket closes the most recent one still open.
Example 2
- Input
- text = "{[(])}"
- Output
- false
The ] arrives while the ( is still open.
Example 3
- Input
- text = "(("
- Output
- false
Two brackets are opened and never closed.
Rules
texthas between 0 and 100,000 characters, all brackets.- An empty string is balanced.
Words on this page, in plain English (2)Open if any word is new to you
- String
- A piece of text, written between quotes. Each letter in it is a character.
- Boolean (true or false)
- A value that can only be
trueorfalse. Like a light switch: on or off.
Answer each question in your own words before you look at ours. Rough notes are fine: the point is to think before you type code. Your answers stay in this browser.
1.What goes in?
Name every input and what it looks like. Can it be empty? Sorted? Negative?
Stuck? Each hint gives a little more away. Try the problem again after each one.
This explains the whole solution.
You will learn the most by trying first, even if you don’t finish. But if this pattern is new to you, reading the walkthrough first is a fine way to learn it.
1. Understand the problem
Three kinds of brackets. Each opening bracket needs a closing bracket of the same kind, and the most recently opened one must close first. ([]) is fine. ([)] is not: the ) tries to close the ( while the [ opened after it is still open.
2. Solve an example by hand
{[()()]}. Read it left to right, keeping a list of what's open: {, then { [, then { [ (. Now ): it closes the last thing opened, (. Back to { [. Then ( and ) again. Then ] closes [, } closes {. Nothing's left open: balanced.
Each closing bracket only ever looked at the last open bracket. Adding at the end and removing from the end: that's a stack.
3. A tempting wrong way
Counting doesn't work: {[(])} has one of each opener and one of each closer, so the counts match, but it isn't balanced. Order matters, and counting forgets order.
4. Spot the pattern
"Things must open and close in order" is the classic stack problem.
5. The stack idea
- An opening bracket: push it onto the stack.
- A closing bracket: pop the stack. The popped bracket must be its matching opener. If the stack was empty or the kind is wrong, it's not balanced.
- At the end, the stack must be empty: anything left was never closed.
Push openers, pop to close
text
open (stack, top first)
- empty
function isBalanced(text) { const opener = { ")": "(", "]": "[", "}": "{" }; // closer → its opener const open = []; // brackets still waiting to be closed for (const char of text) { if (char === "(" || char === "[" || char === "{") { open.push(char); } else if (open.pop() !== opener[char]) { return false; // wrong kind, or nothing open to close } } return open.length === 0;}Start with an empty stack of open brackets.
And one that fails:
Push openers, pop to close
text
open (stack, top first)
- empty
function isBalanced(text) { const opener = { ")": "(", "]": "[", "}": "{" }; // closer → its opener const open = []; // brackets still waiting to be closed for (const char of text) { if (char === "(" || char === "[" || char === "{") { open.push(char); } else if (open.pop() !== opener[char]) { return false; // wrong kind, or nothing open to close } } return open.length === 0;}Start with an empty stack of open brackets.
6. The code, line by line
const opener = { ")": "(", "]": "[", "}": "{" }; // closer → its opener const open = []; // brackets still waiting to be closedopenerlooks up which opener each closer needs, soopener["]"]is"[".openis the stack.for (const char of text) { if (char === "(" || char === "[" || char === "{") { open.push(char);Opening brackets go on the stack.
} else if (open.pop() !== opener[char]) { return false; // wrong kind, or nothing open to close }Anything else is a closer. Pop the most recent open bracket and compare it with what this closer needs. Popping an empty stack gives
undefined, which never matches, so "nothing to close" is handled too.return open.length === 0;Balanced only if nothing is left waiting.
7. How fast is it?
O(n) time: each character is looked at once, and push and pop are instant. O(n) extra memory in the worst case, when everything is an opener.
Common mistakes
- Returning
trueas soon as the loop ends.((never fails a check inside the loop; only the final "is anything still open?" catches it. - Comparing with the first open bracket instead of the last. That's what a queue would do. Brackets need a stack.
Memorise the solution, once you understand it.
This shows the full solution, then helps you rebuild it from memory in four steps. Remembering it is what lets you write it again in an interview, or in a week. Your result goes into your reviews, so it comes back just before you'd forget.
Learn it by heart: Balanced brackets
Read the 12 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function isBalanced(text) { const opener = { ")": "(", "]": "[", "}": "{" }; // closer → its opener const open = []; // brackets still waiting to be closed for (const char of text) { if (char === "(" || char === "[" || char === "{") { open.push(char); } else if (open.pop() !== opener[char]) { return false; // wrong kind, or nothing open to close } } return open.length === 0;}