Valid or Well Formed Parentheses | Part – 1

Objective: You have been asked to Write an algorithm to find Whether Given the Sequence of parentheses are well formed. This question was asked in the Amazon Interview.

Input: A String contains a sequence of parentheses

Output: true or false on whether parentheses are well formed or not


  • Idea is to have two counters, one for open parentheses ‘{‘ and one for close ‘}’
  • Read one character at a time and increment one of the counters
  • If any given point of time count of close parentheses is greater than the open one, return false
  • If at the end both counters are equal, return true

Example: { { } { } } – Well formed

{ { } { = Not well formed

Complete Code:

Is {{{{}}}}{}{}{}{}{}{}{}{}{}{}{{{}}} well formed ??? :true
Is {{{{}}}}{}{}{}{{}{}{}{}{}{}{}{{{}}} well formed ??? :false
Is {}{ well formed ??? :false
Is }{ well formed ??? :false
Is {{{{{{{{}}}}}}}} well formed ??? :true

Top Companies Interview Questions..-


If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

You may also like...

3 Responses

  1. Wonderful site, thanks for sharing !!

  2. Chandra Gopalaiah says:

    My Short and concise solution
    public boolean isWellFormed(String strParentheses) {
    if (strParentheses == null || strParentheses.length() == 0) {
    return false;
    Stack stack = new Stack();
    for (int i=0; i<strParentheses.length();i++) {
    Character c = strParentheses.charAt(i);
    if (c == '}' && (stack.isEmpty() || stack.pop() != '{')) return false;
    if (c == '{') stack.push(c);
    return stack.isEmpty();

  3. Rahul Batheja says:

    given solution is wrong as for the test case “}{ well formed ??? :false” it will return true. so we have to use an stack for this probliem

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: