The (Unofficial) ITWorx Technical Architecture Blog

Interview Question: Is a String of Parenthesis Balanced?

Posted by archworx on May 17, 2007

Here’s an easy one:

Given a string that contains only parenthesis like “(” “[” “)” “]”

We call a string balanced if every opening parenthesis has its corresponding closing parenthesis (and vice versa) , but they have to be in closed in correct order i.e. if you open a nested parenthesis inside another the nested one should be closed before the outer one is closed.

So an example of a balanced string would be “([[(())]])”

Examples of unbalanced strings would be “]([()])[” and “[[[((]))]]”

Can you write a function that takes a string (or characher array) as a parameter and returns true if it is balanced and false if it is not.

Waiting for your answers


5 Responses to “Interview Question: Is a String of Parenthesis Balanced?”

  1. Youssef said

    Not time for a full method, but here’s the algorithm. You mentioned that the string contains ONLY paranthesis. This means that:

    str[n] must be equal to str[length(str)-n] must always be the same char.

  2. Youssef said

    Scratch that.. I think that a balanced parenthesis is more than just the example. Do you have any more examples or test cases?

  3. Here is a simple algorithm:

    for every character:
    if it is an opening parantheses :
    push it on stack s

    if it is a closing parantheses :
    pop the top parantheses from stack s
    if it does not match the closing parantheses :
    string is not balanced

    if the stack not empty:
    string is not balanced
    string is balanced

  4. Alexwebmaster said

    Hello webmaster
    I would like to share with you a link to your site
    write me here

  5. This is really interesting, You are an overly skilled blogger. I’ve joined your rss feed and look forward to in the hunt for extra of your wonderful post. Also, I have shared your site in my social networks!- – London Escorts – Elegant models London, 173A Pavilion Rd, Kensington, Greater London, SW1X 0BJ, 020 3011 2770

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: