R
E
A
C
T
O
xamples
epeat
ode
pproach
ptimize
est
{ Bracket
Balancing }

The Question
One of your colleagues insists on writing all code in Notepad, resulting in code that won't run because the brackets, braces, and parenthesis are not properly balanced. You decide to write a bracket validator to check whether the brackets /braces/ parenthesis are valid.
Notes
- You have already written a RegEx to get rid of the non-brackets from the input string (i.e. your input will be all brackets, parenthesis, and braces)
- For the purpose of the problem these are considered 'brackets':
[ ] ( ) { }
Question
Given an input string return a boolean stating whether or not the brackets are balanced.
What are the expected outputs for each of these?
"{ [ ] ( ) }"
"{ [ ( ] ) }"
"{ [ }"
"{ [ text ( [ is { ( )[ totes]{ f } i } n ] e ) ] }"
One approach
- Each closing bracket should correspond to the nearest opening bracket that it pairs with
- Every opening and closing bracket should be in a pair
- You can keep track of these in a First In Last Out data structure
Approach, continued
{ [ ( ( ) )] }

Approach, continued
{ [ ( ( ) )] }
{

Approach, continued
{ [ ( ( ) )] }
{
{
[

Approach, continued
{ [ ( ( ) )] }
{
{
[
(

Approach, continued
{ [ ( ( ) )] }
{
{
[
(
(

Approach, continued
{ [ ( ( ) )] }
{
{
[
(
(
)

Approach, continued
{ [ ( ( ) )] }
The top bracket closes the one below it, so we can pop them off
{
[
(
(
)

Approach, continued
{ [ ( ( ) )] }
{
(
[

Approach, continued
{ [ ( ( ) ) ] }
{
(
)
The top bracket closes the one below it so pop it
[

Approach, continued
{ [ ( ( ) )] }
{
[

Approach, continued
{ [ ( ( ) ) ] }
{
{
[
]
The top bracket closes the one below it so pop it

Approach, continued
{ [ ( ( ) ) ] }
{

Approach, continued
{ [ ( ( ) ) ] }
{
{
The top bracket closes the one below it so pop it
}

Approach, continued
{ [ ( ( ) ) ] }
We have checked every bracket in the input and since we have no unmatching brackets, we know that the brackets were balanced
What data structure did this approach remind you of ?

What data structure did this approach remind you of ?
a STACK!
Possible Solution

Conclusion
- Data structure principles can come in handy even when you are not explicitly creating a certain structure
- You can use arrays and array methods in Javascript to create an array that basically behaves like a stack/queue
Interview Tips
- There are many ways to solve this!
- Feel free to give them the RegEx, if they begin by saying, I know I could use RegEx but don't know exactly that it would look like..
Bracket Balancing
By mschreiber
Bracket Balancing
Technical interview problem for determining whether the brackets/parenthesis in a string are balanced
- 803