Valid Multiple Parentheses

Objective: Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.

Example:

()()([]({}))[] valid: true
()({]) valid: false
[]{}() valid: true
[(}{)] valid: false

Earlier we had seen problem Valid Parentheses, where only one type of parentheses was present in the input string, in this problem we can have multiple types of parentheses present in the input String. This problem can be considered as extension of Valid Parentheses problem.

Approach:

Using Stack:

  • Initialize a Stack.
  • Iterate the input string, one character at a time.
  • Check if character is open bracket
    • ‘(‘, if yes then push closed bracket ‘)’ to stack.
    • ‘[‘, if yes then push closed bracket ‘]’ to stack.
    • ‘{‘, if yes then push closed bracket ‘}’ to stack
  • Else check if character is close bracket, either ‘)‘ or ‘]’ or ‘}’  if yes then
    • Check if stack is empty, if yes return false.
    • Else if stack is not empty, pop from stack and popped bracket should be same as current bracket else return false.
  • If at the end stack is empty, return true else return false.
  • See the image below for more understanding.
Valid Multiple Parentheses

Complete Code:

Output:

is input ()()([]({}))[] valid: true
is input ()({]) valid: false
is input []{}() valid: true
is input [(}{)] valid: false

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

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

%d bloggers like this: