# Leetcode 20: Valid Parenthesis

## Problem

Given a string `s` containing just the characters `'('``')'``'{'``'}'``'['` and `']'`, determine if the input string is valid.

An input string is valid if:

1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.

leetcode.com/problems/valid-parentheses/

## Constraints:

• `1 <= s.length <= 104`
• `s` consists of parentheses only `'()[]{}'`.

## Solution Approach

For this problem of valid parenthesis, we need a data structure that is capable of containing many characters and which removes the top element whenever the match of the same type of bracket is found that is we need to enter the data in first in first out manner. Therefore, the stack will be the best data structure for this problem.

In the stack, we will first keep adding all the character if they are opening braces, irrespective of its type. If we encounter any closing brace then we will check if that compliments the brace at the top of the stack. In case the complement is present, then we will just remove the top element of the stack. If the complement is not present at the top of the stack then we straight away return false. We also return false when there is nothing in the stack and there is an incoming closing brace of any type. At the end when we go through the complete string and if there is anything present in the stack we return false and if nothing is present in it and all are above conditions are met then we return true from our function.

## Solution Code

For more Leetcode explained solutions visit Leetcode Solutions. If you like capture the flag challenges visit here.

Check out my socials below in the footer. Feel free to ask any doubts in comment section or contact me via Contact page I will surely respond. Happy Leetcoding ðŸ™‚