LeetCode Series: Valid Parenthesis Problem

The Question is from the interview section of leetcode and is marked as easy difficult. Here is the description:

The 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.
  3. Every close bracket has a corresponding open bracket of the same type.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

The Solution

var ValidParenthesis = function(str) {
    if(str.length == 1){
        return false; 
    }
    let obj = {
        '(': ')',
        '{': '}',
        '[':  ']'
    }
    let objKeys = ['(', '{', '['];
    let arr = [];
    let length = str.length;
    let i = 0;
    while(i<length){
        if(objKeys.includes(str[i])){
            arr.push(str[i]);
            i++;
        }else{
            let ch = arr.pop();
            if(ch=='(' && str[i] == ')' || ch=='[' && str[i] == ']' || ch=='{' && str[i] == '}'){
                i++;
            }else{
                return false;
            }
        }
    }
    if(arr.length == 0){
        return true;
    }else{
        return false;
    }
};

Watch the video for a full code walkthrough and optimisation steps. If you do have any questions or feedback feel free to add comments.

manorinfinity Written by:

Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being

Be First to Comment

Leave a Reply

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