Skip to content

Instantly share code, notes, and snippets.

@amitasaurus
Last active May 5, 2024 04:04
Show Gist options
  • Save amitasaurus/505b22cc8f87301f5a634adfdca69770 to your computer and use it in GitHub Desktop.
Save amitasaurus/505b22cc8f87301f5a634adfdca69770 to your computer and use it in GitHub Desktop.
The validParentheses function takes a string containing various types of parentheses ((), {}, []) as input and checks whether the arrangement of parentheses is valid. It returns true if the input string contains a valid arrangement of parentheses, meaning that for every opening parenthesis, there is a corresponding closing parenthesis in the cor…
function validParentheses(str: string): boolean {
const stack: string[] = [];
const map: Record<string, string> = {
'}': '{',
')': '(',
']': '[',
};
for (let index = 0; index < str.length; index++) {
const char = str[index];
if (map[char]) {
if (stack.length > 0 && stack[0] === map[char]) {
stack.shift();
} else {
stack.unshift(char);
}
} else {
stack.unshift(char);
}
}
return stack.length === 0;
}
console.log('{{}}()[()]', validParentheses('{{}}()[()]')); // true
console.log('{][}', validParentheses('{][}')); // false
console.log(')', validParentheses(')')); // false
console.log('{}', validParentheses('{}')); // true
console.log('()', validParentheses('()')); // true
console.log('({})', validParentheses('({})')); // true
console.log('((()))', validParentheses('((()))')); // true
console.log('[(])', validParentheses('[(])')); // false
console.log('{[()()]}', validParentheses('{[()()]}')); // true
console.log('(({[]}))', validParentheses('(({[]}))')); // true
@amitasaurus
Copy link
Author

The valid parentheses problem involves checking that:

all the parentheses are matched, i.e., every opening parenthesis has a corresponding closing parenthesis.
the matched parentheses are in the correct order​, i.e., an opening parenthesis should come before the closing parenthesis.

Algorithm
Declare an empty stack.
Push an opening parenthesis on top of the stack.
In case of a closing bracket, check if the stack is empty.
If not, pop in a closing parenthesis if the top of the stack contains the corresponding opening parenthesis.
If the parentheses are valid,​ then the stack will be empty once the input string finishes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment