This approach uses a stack to efficiently match opening and closing brackets. The stack stores opening brackets, and for each closing bracket encountered, it checks if it closes the last opened bracket (top of the stack).
Time Complexity: O(n), where n is the length of the string, since we process each character once.
Space Complexity: O(n) in the worst case if the string consists only of opening brackets.
1function isValid(s) {
2 const stack = [];
3 const map = {
4 ')': '(',
5 '}': '{',
6 ']': '['
7 };
8 for (const char of s) {
9 if (map[char]) {
10 if (stack.pop() !== map[char]) {
11 return false;
12 }
13 } else {
14 stack.push(char);
15 }
16 }
17 return stack.length === 0;
18}
19
20console.log(isValid("()[]{}")); // Output: true
21console.log(isValid("(]")); // Output: false
The JavaScript solution uses an array as a stack for keeping track of open brackets and a map to match them with closing brackets, ensuring a valid structure of the input string.
This approach uses two pointers with stack-like behavior internally, taking advantage of simple list operations for push and pop.
Time Complexity: O(n)
Space Complexity: O(n/2) = O(n)
1function isValid(s) {
2 if (s.length % 2 !== 0) return false;
3
4 const stack = [];
5 for (let char of s) {
6 if (char === '(' || char === '{' || char === '[') {
7 stack.push(char);
8 } else {
9 if (stack.length === 0) return false;
10 const top = stack.pop();
11 if (!((char === ')' && top === '(') ||
12 (char === '}' && top === '{') ||
13 (char === ']' && top === '['))) {
14 return false;
15 }
16 }
17 }
18 return stack.length === 0;
19}
20
21console.log(isValid("()[]{}")); // Output: true
22console.log(isValid("(]")); // Output: false
The JavaScript implementation checks for an even length initially, then processes each character with a conventional stack dynamics rooted in array handling - verifying the lock-and-key representation of valid parentheses.