# Balanced Brackets

Problem source: Balance Brackets – Hackerrank

Sample Input:

``````{[()]}
{[(])}
{{[[(())]]}}``````

Output:

``````YES
NO
YES
``````

Algorithm:

The logic is quite simple, first check for basic failure conditions like,

• Total numbers of characters are odd
• First character is end of brackets like ‘)’, ‘}’, ‘]’

If basic checks are clear then we need to check for traverse whole input string and match start and end brackets and to do so we can use STACK. Follow below rules to verify perfect match:

1. For every start bracket like ‘(‘, ‘{‘, ‘[‘, push it to stack.
2. If Stack is empty and next bracket is ‘)’ or ‘}’ or ‘]’ then then it’s a failure.
3. If Stack is not empty then check whether current item and popped item is match or not if not then it’s a failure.

Code in C#:

```static void StackMethod()
{
for (int i = 0; i < n; i++)
{
Stack<char> balancedBracket = new Stack<char>();
bool isMatched = true;
if (strInput.Length % 2 != 0 || strInput[0] == ')'
|| strInput[0] == '}' || strInput[0] == ']')
{
Console.WriteLine("NO");
continue;
}

foreach (var item in strInput)
{
if (item == '(' || item == '{' || item == '[')
{
balancedBracket.Push(item);
}
else if (balancedBracket.Count == 0 && (item == ')'
|| item == '}'
|| item == ']')
)
{
isMatched = false;
break;
}
else if (balancedBracket.Count > 0 && ((item == ')'
&& balancedBracket.Pop() != '(')
|| (item == '}' && balancedBracket.Pop() != '{')
|| (item == ']' && balancedBracket.Pop() != '[')
))
{
isMatched = false;
break;
}
}
if (isMatched && balancedBracket.Count == 0)
{
Console.WriteLine("YES");
}
else
{
Console.WriteLine("NO");
}
}