Balanced Paranthesis Coding Question — Asked in Google, Amazon

Placewit
2 min readMar 13, 2022

Problem Statement:

For a given a string expression containing only round brackets or parentheses, check if they are balanced or not. Brackets are said to be balanced if the bracket which opens last, closes first.

Input Format:

The first and the only line of input contains a string expression without any spaces in between.

Output Format:

The only line of output prints ‘true’ or ‘false’.

Sample Input 1 :

(()()())

Sample Output 1 :

true

Sample Input 2 :

()()(()

Sample Output 2 :

false

Explanation of Sample Input 2:

The initial two pairs of brackets are balanced. But when you see, the opening bracket at the fourth index doesn't have its corresponding closing bracket which makes it imbalanced and in turn, making the whole expression imbalanced. Hence the output prints 'false'.

Code:

Thanks for Reading

Placewit grows the best engineers by providing an interactive classroom experience and by helping them develop their skills and get placed in amazing companies.

Learn more at Placewit. Follow us on Instagram and Facebook for daily learning.

--

--