Dsa
Stack
Hard
Balanced Parentheses with Count
Write a program that checks whether the parentheses ( ) and brackets [ ] in a given string are balanced. Additionally, count the number of balanced pairs. A pair is defined as a matching set of parentheses or brackets. The input string may contain letters and numbers but should only count parentheses and brackets for balancing. Output the count of the balanced pairs along with whether the string is balanced or not.
Input format:
A single line containing the input string.
Output format:
Print 'Balanced' or 'Not Balanced' depending on the string, followed by the count of balanced pairs.
Example:
Input:
( [ ] ) a { x y }
Output:
Balanced 3
Key concepts
stackparenthesescounting
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now