Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Checking the validity of parentheses in JavaScript
We are required to write a JavaScript function that takes in a string containing just the characters:
'(', ')', '{', '}', '[' and ']'
Our function should determine if the input string is valid.
An input string is valid if:
-
Open brackets must be closed by the same type of brackets.
-
Open brackets must be closed in the correct order.
For example:
-
"()" is a valid parenthesis
-
"()[]{}" is a valid parentheses
-
"(]" is an invalid parenthesis
Algorithm
We'll use a stack data structure approach:
-
Push opening brackets onto the stack
-
For closing brackets, check if they match the last opening bracket
-
If the stack is empty at the end, all brackets were properly matched
Example
const str1 = "()[]{}"
const str2 = "(]"
const isValid = (str = '') => {
const map = new Map()
map.set('{', '}')
map.set('(', ')')
map.set('[', ']')
const stack = []
for (let i = 0; i < str.length; i++) {
const char = str.charAt(i)
if (map.has(char)) {
// Opening bracket - push to stack
stack.push(char)
} else {
// Closing bracket - check if it matches
let pop = stack.pop()
if (map.get(pop) !== char) {
return false
}
}
}
return stack.length === 0
}
console.log("Testing '" + str1 + "':", isValid(str1))
console.log("Testing '" + str2 + "':", isValid(str2))
Output
Testing '()[]{]': true
Testing '(]': false
Testing Multiple Cases
const testCases = ["()", "()[]{}", "(]", "([)]", "{[]}"]
testCases.forEach(test => {
console.log(`"${test}": ${isValid(test)}`)
})
"()": true
"()[]{]": true
"(]": false
"([)]": false
"{[]}": true
How It Works
The algorithm uses a Map to store bracket pairs and a stack (array) to track opening brackets. When encountering an opening bracket, it's pushed onto the stack. For closing brackets, we pop the last opening bracket and verify they match. If the stack is empty after processing, all brackets were properly closed.
Conclusion
This stack-based approach efficiently validates parentheses in O(n) time complexity. The key insight is matching closing brackets with their corresponding opening brackets in the correct order.
