Scriptdrill

Level 1: Basics Exercise 15 of 76 Free

Balanced brackets

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Return `true` when every opening bracket in `s` (one of `(`, `[`, `{`) is closed by the matching closing bracket in the right order, and `false` otherwise. Characters that are not brackets are ignored, so `"f(x[0])"` is balanced and `"(]"` and `"([)]"` are not. A string with no brackets, including the empty string, is balanced.

What this exercise teaches

A stack remembers which bracket is currently open, so a closing bracket is checked against the most recent one. Counting brackets per type cannot tell ([)] from ([]) because the counts are the same in both.

A hint if you get stuck

Use an array as a stack: push every opening bracket, and on a closing bracket pop and check that the popped one is its partner. At the end the stack must be empty.

Try it now, free, no account needed

Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Basics