# Matching parenthesis problem

We understood the concept of stack data structure in last post. Let’s discuss matching parenthesis problemwhich applies those concept. Problem statement is :

Given a string of parenthesis ‘(‘ and ‘)’, write a function which returns true if there are matching pairs and false if there are not. A matching pair means, there should be a closing parenthesis for an opening one, in correct order.

For example : `'((()))'`, function should return `TRUE`, but `')(())'` will return `FALSE`. Special case would be when there are equal number of parenthesis, closing and opening, but they are not in perfect order, hence function should return false in that case.

## Parenthesis matching problem : Line of thoughts

For each closing parenthesis, we need a corresponding opening parenthesis. There are two possibilities : Either we find one or we do not find one. If we do not find one, we can say that string does not contain matching parenthesis.
If there is corresponding opening parenthesis, then that opening parenthesis cannot be matched with any other closing parenthesis.

Also, note that every closing parenthesis will match with the most recent opening parenthesis if there is one. That means we are looking at a order where the parenthesis which came last needs to be fetched first, typical last in first out pattern, which is best implemented by stack.

For asserting that the current closing parenthesis is in sync with what we have already seen, we just need to check if current parenthesis completes a pair with opening parenthesis we last seen. Next closing parenthesis should complete pair with the one prior to last and so on.

### Parenthesis matching problem : Algorithm

1. For each character of input string
2. If character is opening parenthesis `'('`, put it on stack.
3. If character is closing parenthesis `')'`
1. Check top of stack, if it is `'('` , pop and move to next character.
2. If it is not `'('`, return false
4. After scanning the entire string, check if stack is empty. If stack is empty, return true else return false.

### Matching parenthesis problem : Implementation

```package com.company;

import java.util.Stack;

/**
* Created by sangar on 21.9.18.
*/
public class ParenthesisMatch {

public static boolean isMatchingParenthesis(String s) {
Stack<Character> stack = new Stack<>();

if (s == null) return true;

int len = s.length();
for(int i=0; i<len; i++){
switch(s.charAt(i)){
case '(' :
stack.push(s.charAt(i));
break;
case ')':
//If stack is empty, then there is an extra closing parenthesis
if(stack.isEmpty()) return false;
stack.pop();
break;
default:
return false;
}
}
//If stack is empty that means it's a matching parenthesis
return stack.empty();
}

public static void main(String[] args) {
String s = "()))";
System.out.println(isMatchingParenthesis(s));
}
}
```

Complexity of parenthesis matching algorithm is `O(N)` time to scan N length string and `O(N)` extra space for stack.
This problem is quite simple to solve, so if you are asked this question in interview, most probably interviewer wants to understand can you think of good test cases and put your code to test against them. Below are the few test cases you can try your code on.
Test cases

```1. ((())) : True
2. ())) : False
3. )((( : False
4. ( : False
5 Empty string : True
6. NULL pointer : False
```

Can you try solving this problem now on HackerEarth

Please share if there is something wrong or missing. If you are interested to take personal coaching from our experience teachers, please reach out to us at [email protected]