Check the brackets in a config template

EasyAbout 15 minProblem 1 of 2 in StacksDraft

The problem

A config template uses (), [] and {}. Before it is rendered, check that every bracket closes the most recent bracket still open, with the matching kind, and that nothing is left open.

Other characters do not matter. Return true if the brackets are balanced and false otherwise.

  • 0 ≤ text.length ≤ 200,000

Examples

  1. balanced("{ \"ports\": [80, 443], \"tls\": (on) }")returns true
  2. balanced("([)]")returns falseThe ] closes a ( that is still open inside.
  3. balanced("{{")returns falseLeft open.

Hints

Hint 1 of 2

When a closing bracket arrives, which opening bracket must it match?

Hint 2 of 2

Push each opening bracket. On a closing bracket, pop and compare. At the end the stack must be empty.

Editorial

Opens once you solve the problem, or after three checked attempts.

Your solution

Tab indents. Press Esc, then Tab, to leave the editor. Ctrl+Enter runs the examples.

Esc
↑ ↓ to move↵ to open