Education logo

Coding: Valid Parentheses Checker in JavaScript

A JavaScript function to determine if a string of parentheses is valid or not

By Monu Kumar ModiPublished 3 years ago 3 min read

Introduction: Parentheses are fundamental in programming for grouping expressions, controlling order of operations, and defining function parameters. Ensuring the correctness of parentheses placement is crucial for maintaining code integrity. In this comprehensive guide, we will explore in detail how to validate parentheses in JavaScript, using an efficient algorithm.

I. The Problem of Validating Parentheses: When working with strings that contain parentheses, it becomes necessary to determine whether the parentheses are balanced or not. A balanced string of parentheses means that for every opening parenthesis, there exists a corresponding closing parenthesis in the correct order. For example, the string "([])" is balanced, while "(])" is not.

II. Approach: Using a Stack Data Structure: To solve the problem of validating parentheses, we will employ a stack data structure. A stack follows the Last-In-First-Out (LIFO) principle, making it well-suited for checking balanced parentheses. The algorithm can be summarized as follows:

1. Initialize an empty stack.

2. Iterate through the input string character by character.

3. If the current character is an opening parenthesis, push it onto the stack.

4. If the current character is a closing parenthesis:

(a) Check if the stack is empty. If it is, return false as there is no corresponding opening parenthesis.

(b) If the stack is not empty, compare the current closing parenthesis with the top element of the stack.

(c) If they match, pop the top element from the stack, indicating a successful match.

(d) If they don't match, return false as the parentheses are not balanced.

5. after iterating through all the characters in the string, check if the stack is empty.

(a) If the stack is empty, return true, indicating that the parentheses are balanced.

(b) If the stack is not empty, return false, indicating that there are unmatched opening parentheses.

III. Implementing the Algorithm in JavaScript:

Let's implement the algorithm in JavaScript using the following code snippet:

function isValid(s) {

const hashMap = { '(': ')', '{': '}', '[': ']' }

const stack = []

for (let ch of s) {

if (hashMap[ch]) {

stack.push(hashMap[ch])

} else if (stack.length > 0 && stack[stack.length - 1] == ch) {

stack.pop()

} else {

return false

}

}

return stack.length === 0

}

let str1 = '([])'

console.log(isValid(str1))

IV. Analyzing the Time and Space Complexity: The time complexity of the algorithm is linear, O(n), where 'n' is the length of the input string. This is because we iterate through the string only once.The space complexity is also linear, O(n), as the maximum space used by the stack is proportional to the number of parentheses in the input string.

V. Testing the Algorithm: To verify the correctness of the isValid function, we can test it with various string inputs that contain parentheses. It is recommended to test with strings like "([])", "({})", "((()))", and "([)]" to cover different scenarios and validate the algorithm's performance.

Conclusion:

  • Validating parentheses is a crucial task in programming, ensuring that expressions and code structures are correctly balanced. In this comprehensive guide, we explored the algorithm to validate parentheses in JavaScript, using a stack data structure.
  • By utilizing a stack, we can efficiently check whether a given string of parentheses is balanced or not. The algorithm iterates through the input string, pushing opening parentheses onto the stack and popping them when a corresponding closing parenthesis is encountered. If the stack is empty at the end of the iteration, it indicates that all parentheses have been matched, and the string is considered valid.
  • The implementation of the algorithm in JavaScript was demonstrated with the isValid function. The function takes an input string and returns true if the parentheses are balanced and false otherwise. The code snippet showcased the step-by-step execution of the algorithm, utilizing a hashMap to map opening parentheses to their corresponding closing parentheses.
  • We also discussed the time and space complexity of the algorithm. The time complexity is linear, O(n), as the algorithm iterates through the string once. The space complexity is also linear, O(n), as the stack's space usage is proportional to the number of parentheses in the input string.
  • To validate the algorithm, we tested the isValid function with the input string "([])". The output of the test was true, confirming that the string of parentheses is valid.
  • In conclusion, the algorithm presented in this guide provides an efficient and reliable solution for validating parentheses in JavaScript. By understanding the underlying principles and implementing the algorithm correctly, developers can ensure the integrity and correctness of parentheses placement in their code.

interviewstudentcollege

About the Creator

Monu Kumar Modi

Monu Kumar, Full Stack Developer.

Make code magic happen #Javascript | Let the code work its magic | Linkedin

Reader insights

Be the first to share your insights about this piece.

How does it work?

Add your insights

Comments

There are no comments for this story

Be the first to respond and start the conversation.

Sign in to comment

    Find us on social media

    Miscellaneous links

    • Explore
    • Contact
    • Privacy Policy
    • Terms of Use
    • Support

    © 2026 Creatd, Inc. All Rights Reserved.