Skip to content

Instantly share code, notes, and snippets.

@Trepix
Last active February 24, 2021 22:39
Show Gist options
  • Save Trepix/93b0c584f62e338248a760c29e3e8f96 to your computer and use it in GitHub Desktop.
Save Trepix/93b0c584f62e338248a760c29e3e8f96 to your computer and use it in GitHub Desktop.
Balanced Brackets

Balanced Brackets

First step

Take an input string with X opening brackets [ and Y closing brackets ], in a random order.

Determine if the generated string of brackets is balanced, that is it consists of pairs of opening/closing brackets in the correct order with no matched opening and closing pairs.

Do not worry about input other than brackets and empty string.

Examples

(empty) “” OK
[] OK
[][] OK
[[]] OK
[[[][]]] OK
][ FAIL
][][ FAIL
[][]][ FAIL

Second step

Add parentheses () to the validation. Brackets and parentheses can be combined at any way while they respect the opening/closing rule.

Examples

[) FAIL
()[] OK
[(]) FAIL
([()]) OK

Third step

Add curly braces {} to the validation. They can be combined following the same previous rules

Examples

[]{ FAIL
[]{}() OK
[(){]} FAIL
[({})] OK 

Fourth step

Also validate the order.

  • Parentheses can only contain parentheses or nothing
  • Brackets can contain brackets, parentheses or nothing
  • Curly braces can contain curly braces, brackets, parentheses or nothing

Examples

([()]) FAIL
[]{}() OK
[(){}] FAIL
[()[]] OK
{[()]} OK
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment