Skip to content

Commit

Permalink
feat: Add solution for valid-parentheses problem
Browse files Browse the repository at this point in the history
  • Loading branch information
pragusga25 committed Jul 17, 2024
1 parent 673066c commit 8159530
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions easy/valid-parentheses.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Problem: https://leetcode.com/problems/valid-parentheses/
// Doc: https://leetcode.com/problems/valid-parentheses/solutions/5491623/efficient-solution-for-valid-parentheses/
const isValid = (s: string): boolean => {
const stack: string[] = [];

const parClosedMap = {
')': '(',
'}': '{',
']': '[',
};

for (let i = 0; i < s.length; i++) {
const char = s[i];
if (!(char in parClosedMap)) {
stack.push(char);
continue;
}

const popped = stack.pop();
if (!popped) return false;
const opened = parClosedMap[char];
if (popped !== opened) return false;
}

return stack.length === 0;
};

describe('Valid Parentheses', () => {
it('should return true for valid parentheses', () => {
expect(isValid('()')).toBe(true);
expect(isValid('()[]{}')).toBe(true);
expect(isValid('{[]}')).toBe(true);
expect(isValid('([{}])')).toBe(true);
});

it('should return false for invalid parentheses', () => {
expect(isValid('(]')).toBe(false);
expect(isValid('([)]')).toBe(false);
expect(isValid('[')).toBe(false);
expect(isValid(']')).toBe(false);
});
});

0 comments on commit 8159530

Please sign in to comment.