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()
{
    int n = Convert.ToInt32(Console.ReadLine());
    for (int i = 0; i < n; i++)
    {
        Stack<char> balancedBracket = new Stack<char>();
        string strInput = Console.ReadLine();
        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");
        }
    }
    Console.ReadKey();
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s