educative.io

Educative

Solution Balanced Brackets problem

I understand that the solution to this problem relies on the value of check meaning that there must be an equal number of opening and closing brackets.

However what I don’t understand is why it still works for ‘][’ or ‘[]][’

1 Like

Hi @Mauricio1,

Good observation, but there is a catch.
case ][
If the program gets ] (closing bracket) before [ opening bracket then check will become less than 0 and as the program is checking for check < 0 in every iteration of the loop. Thus, it will break and return false.
case []][
In the first iteration of the loop when bracket contains [, check will become 1, moving on to the 2nd iteration where bracket contains [, check will become 0 but will not return true as the loop breaks only if check < 0. In the 3rd iteration, when bracket contains ], check will become -1 which causes the loop to break and return false.

P.S. Please look into the screenshot attached for reference:
Screenshot 2022-03-16 at 11.33.54 AM

Hope this clears the confusion

1 Like

can u help with this bracket ‘[[[[]]’, which has more opening brackets than closing ones, after the sample code runs thru each iteration the output should not meet the break condition?

Thx!

Hi @UniThe_G ,

As the bracket_string contains four "[" (opening brackets) initially thus after 4 iterations, check will contain 4. In the 5th and 6th iteration, as bracket contains ], thus check will become 2 (4 - 2 = 2).

Hence, check == 0 will become false.
Screenshot 2022-03-18 at 1.28.03 PM

P.S. In this case, loop will not break but we get false because after completing the loop, check contains 2, so check == 0(line 13) will return false.

Hope this clears the confusion

1 Like

Sami thanks a lot for the clarification

Thank you very much Sami =D