Skip to content
Algorithms for Beginners

Problems / Stack

Balanced brackets

easy

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. 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

  1. Example 1

    Input
    text = "{[()()]}"
    Output
    true

    Each bracket closes the most recent one still open.

  2. Example 2

    Input
    text = "{[(])}"
    Output
    false

    The ] arrives while the ( is still open.

  3. Example 3

    Input
    text = "(("
    Output
    false

    Two brackets are opened and never closed.

Rules

  • text has 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 true or false. Like a light switch: on or off.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function isBalanced(text) {
  // Return true or false.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in stack

  • Learn the stack pattern

    Keep the most recent unfinished thing on top, and finish it first.

  • Typing with backspace

    Easy. Work out what's on the screen after someone types, including presses of the backspace key.

  • Stack with minimum

    Medium. Build a stack that can also tell you its smallest item instantly.

  • Postfix calculator

    Medium. Work out a sum written with the operators after the numbers, like 3 4 + 2 *.

  • Tidy a file path

    Medium. Turn a messy folder path with dots and extra slashes into its simplest form.

  • Days until warmer

    Medium. For each day, count how many days you'd wait for a warmer one.