The Wayback Machine - https://web.archive.org/web/20240619224452/https://www.geeksforgeeks.org/javascript-program-to-check-valid-parentheses-using-string/
Open In App

JavaScript Program to Check Valid Parentheses Using String

Last Updated : 31 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how we can check valid parentheses of a string, and write a program to check whether the pairs and order of “{ “, ” } “, “(“, “)”, “[“, “]” in the string expression is right or not.

Example:

Input: exp = "[()][()()]()" 
Output: True.
Explanation: all of the brackets are properly formed.
Input: exp = "[(])"
Output: False
Explanation: The first and fourth brackets are not balanced because there is a closing ']' before the final '('.

Using the Stack

This method involves using a stack data structure to keep track of parentheses and ensuring they are properly closed.

  • Begin by initializing a stack.
  • Iterate, through the given string.
  • If an open parenthesis is encountered, push it onto the stack.
  • If a closing parenthesis is encountered check if it matches the element of the stack.
  • If they match, pop the element from the stack; otherwise conclude that the parentheses are not balanced and return false.
  • After iterating through all characters in the string if the stack is empty it means all parentheses have been correctly closed so return true.

Syntax:

stackname.push(value);
stackname.pop()
Javascript
function isValidParentheses(str) {
    const stack = [];
    const pairs = {
        "(": ")",
        "[": "]",
        "{": "}",
    };

    for (let char of str) {
        if (pairs[char]) {
            stack.push(char);
        } else if (
            char === ")" ||
            char === "]" ||
            char === "}"
        ) {
            if (
                pairs[stack.pop()] !==
                char
            ) {
                return false;
            }
        }
    }

    return stack.length === 0;
}

const inputString = "({()})";
console.log(
    `Is it a valid Paranthesis ? :
${isValidParentheses(inputString)}`
);

Output
Is it a valid Paranthesis ? :
true

Using Counter

This approach relies on using a counter to keep track of the balance between closing parentheses.

  • Start by initializing a counter variable.
  • Iterate through each character in the given string.
  • Increment the counter whenever an open parenthesis is encountered and decrement it for each closing parenthesis found.
  • If at any point during iteration the counter becomes negative it implies that there are closing parentheses than opening ones; thus return false.
  • Once finished iterating through all characters in the string if the counter equals zero it indicates that all parentheses have been properly balanced, hence return true.

Syntax:

for ( variable of iterableObjectName) {
...
}
Javascript
function isValidParentheses(str) {
    let count = 0;

    for (let char of str) {
        if (char === "(") {
            count++;
        } else if (char === ")") {
            if (count === 0) {
                return false;
            }
            count--;
        }
    }

    return count === 0;
}

const inputString = "((()))";
console.log(
    `Is it a valid Paranthesis ? :
${isValidParentheses(inputString)}`
);

Output
Is it a valid Paranthesis ? :
true

Using Regular Expression

In this method we employ expressions to repeatedly remove valid pairs of parentheses until none remain.

  • Define an expression pattern that matches pairs of parentheses.
  • Enter into a loop that finds and removes pairs using replace operations with a string as replacement text.
  • Repeat step 2 until no valid pairs can be found in iterations (i.e. after performing replacements without finding any matches).
  • If, after completing these iterations our initial string becomes empty it means all parentheses have been successfully matched and eliminated; thus return true. Otherwise return false.

Syntax:

/pattern/modifiers;
Javascript
function isValidParentheses(str) {
    const regex = /(\(\)|\[\]|\{\})/g;

    while (str.match(regex)) {
        str = str.replace(regex, "");
    }

    return str.length === 0;
}

const inputString = "{[()]]}";
console.log(
    `Is it a valid Paranthesis ?
${isValidParentheses(inputString)}`
);

Output
Is it a valid Paranthesis ?
false

Using a Map for Character Matching

This method uses a stack and a Map to match opening and closing brackets. As characters are processed, opening brackets are pushed onto the stack. When a closing bracket is encountered, it is checked against the stack’s top. The string is valid if the stack is empty.

Example: In this example The function isValidParentheses checks if a given string of parentheses is valid. It utilizes a stack and a map to match opening and closing parentheses. The examples demonstrate its correctness.

JavaScript
function isValidParentheses(s) {
    const stack = [];
    const matchingBrackets = new Map([
        ['(', ')'],
        ['{', '}'],
        ['[', ']']
    ]);

    for (let char of s) {
        if (matchingBrackets.has(char)) {
            stack.push(char);
        } else {
            if (stack.length === 0 || matchingBrackets.get(stack.pop()) !== char) {
                return false;
            }
        }
    }

    return stack.length === 0;
}

console.log(isValidParentheses("(){}[]")); 
console.log(isValidParentheses("([{}])")); 
console.log(isValidParentheses("(]"));     

Output
true
true
false

Using a recursive function

This approach recursively removes pairs of matching parentheses until either all parentheses are balanced or an imbalance is detected. It continues this process until the string is empty or an imbalance is found, returning true if the parentheses are balanced and false otherwise.

JavaScript
function isValidParentheses(str) {
    // Recursive function to check the balance of parentheses
    const checkBalance = (s) => {
        // Base case: empty string
        if (s.length === 0) return true;

        // Find the index of the first closing parenthesis
        const closingIndex = s.indexOf(')');
        if (closingIndex === -1) return false; // If no closing parenthesis is found, parentheses are unbalanced

        // Find the index of the nearest opening parenthesis before the closing parenthesis
        const openingIndex = s.lastIndexOf('(', closingIndex);
        if (openingIndex === -1) return false; // If no opening parenthesis is found, parentheses are unbalanced

        // Remove the matched parentheses and continue checking the balance
        const remaining = s.slice(0, openingIndex) + s.slice(openingIndex + 1, closingIndex) + s.slice(closingIndex + 1);
        return checkBalance(remaining);
    };

    // Call the recursive function
    return checkBalance(str);
}

const inputString = "({()})";
console.log(`Is it a valid Paranthesis ? : ${isValidParentheses(inputString)}`);

Output
Is it a valid Paranthesis ? : false




Similar Reads

Check if a string is a valid JSON string using JavaScript
We will be given a string and we need to validate whether the given string is a valid JSON string or not. JSON string is the same as a javaScript object and it must follow the syntax of that object. If the syntax is correct then we have to return true or we have to return false. Methods to Check if a String is Valid JSON String: Table of Content Me
4 min read
JavaScript Check if a string is a valid hex color representation
Given a hex color code and the task is to check whether the given hexCode is valid or not using JavaScript. We are going to discuss a few techniques. Approach: Valid hexcode contains the alphabets(A-F) and integers(0-9) and is of length 3 or 6.A RegExp is used to check whether the alphabets ranging between A and F, Integers from 0-9, and is of leng
1 min read
How to Check if a String Contains a Valid URL Format in JavaScript ?
A string containing a valid URL format adheres to standard conventions, comprising a scheme (e.g., "http://" or "https://"), domain, and optionally, a path, query parameters, and fragments. Ensuring this format is crucial for data consistency and accurate handling of URLs in applications. There are several methods that can be used to check if a str
2 min read
How to check if a string is a valid IP address format in JavaScript ?
In this article, we will see how to check if a string is a valid IP address or not. An IP address is a unique identifier assigned to each device connected to a computer network that uses the Internet Protocol for communication. There are two common formats for IP addresses: IPv4 and IPv6. Checking if a string is a valid IP address format in JavaScr
3 min read
JavaScript program to Check the Expression has valid or Balanced Parenthesis or Not
Given the expression string, Our task is to Check whether the expression has valid or Balanced parenthesis or not in JavaScript. Valid input refers to every bracket having its corresponding bracket of the same type in the correct order. Example: Input: exp = "[()][()()]()" Output: True.Explanation: All of the brackets are balanced.Input: exp = "[(]
3 min read
How to check a date is valid or not using JavaScript ?
To check if a date is valid or not in JavaScript, we have to know all the valid formats of the date for e.g."YYYY/DD/MM","DD/MM/YYYY", and "YYYY-MM-DD", etc. we will have a given date format and we need to check whether that given format is valid or not according to the official and acceptable date format. There are two methods to solve this proble
4 min read
How to check if a string is valid MongoDB ObjectId in Node.js ?
MongoDB ObjectId: MongoDB creates a unique 12 bytes ID for every object using the timestamp of respective Object creation.This ObjectId can be used to uniquely target a specific object in the database. Structure: 4-byte timestamp value5-byte random value3-byte incrementing counter, initialized to a random value It looks like this, 507f191e810c19729
2 min read
Less.js Mixins With Parentheses
Less.js is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is preferable since CSS is a dynamic style sheet language. LESS can be utilized by many different browsers because it is versatile. Web browsers can only use CSS that has been developed and processed using a co
3 min read
How to check whether a form or a control is valid or not in Angular 10 ?
In this article, we are going to check whether a form is touched or not in Angular 10. The valid property is used to report that the control or the form is valid or not. Syntax: form.valid Return Value: boolean: the boolean value to check whether a form is valid or not. NgModule: Module used by the valid property is: FormsModule Approach: Create th
1 min read
Check valid Substring of at least k length
Given a string s ('a' <= s[i] <= 'z') and an integer k (1 <= k < n <= 105), the task is to check if any valid substrings of at least k length exist in the given string. A substring is valid if the occurrences of each character in the substring should be even. Examples: Input: s = “bba”, k = 2Output: trueExplanation: Below is valid su
5 min read