| 7 | 7 | * @param {string} input |
| 8 | 8 | * @returns {boolean} |
| 9 | 9 | */ |
| 10 | export const isPaired = (input) => { | |
| 11 | throw new Error('Remove this line and implement the function'); | |
| 10 | const isPaired = (input) => { | |
| 11 | const stack = []; | |
| 12 | const pairs = { | |
| 13 | ']': '[', | |
| 14 | '}': '{', | |
| 15 | ')': '(' | |
| 16 | }; | |
| 17 | ||
| 18 | // Edge Case: empty string | |
| 19 | if (input.length === 0) { | |
| 20 | return true; | |
| 21 | } | |
| 22 | ||
| 23 | for (let i = 0; i < input.length; i++) { | |
| 24 | const char = input[i]; | |
| 25 | ||
| 26 | // If it's an opening bracket, push to stack | |
| 27 | if (char === '[' || char === '{' || char === '(') { | |
| 28 | stack.push(char); | |
| 29 | } | |
| 30 | // If it's a closing bracket | |
| 31 | else if (char === ']' || char === '}' || char === ')') { | |
| 32 | // Edge Case: unmatched closing bracket (stack is empty) | |
| 33 | if (stack.length === 0) { | |
| 34 | return false; | |
| 35 | } | |
| 36 | ||
| 37 | // Edge Case: wrongly nested brackets (mismatched pair) | |
| 38 | if (stack.pop() !== pairs[char]) { | |
| 39 | return false; | |
| 40 | } | |
| 41 | } | |
| 42 | // Ignore all other characters | |
| 43 | } | |
| 44 | ||
| 45 | // Edge Case: unmatched opening brackets (stack is not empty) | |
| 46 | return stack.length === 0; | |
| 12 | 47 | }; |
| 48 | ||
| 49 | module.exports = { isPaired }; | |
| 50 |