Skip to content

Commit 676af57

Browse files
authored
Merge pull request #1575 from ivanpenaloza/march14
adding algo
2 parents 9bb878d + 9274589 commit 676af57

5 files changed

Lines changed: 177 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def twoSum(self, nums: List[int], target: int) -> List[int]:
6+
7+
answer = dict()
8+
9+
for k, v in enumerate(nums):
10+
11+
if v in answer:
12+
return [answer[v], k]
13+
else:
14+
answer[target - v] = k
15+
16+
return []
17+
18+
19+
20+
21+
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
import re
4+
5+
class Solution:
6+
def isPalindrome(self, s: str) -> bool:
7+
8+
# To lowercase
9+
s = s.lower()
10+
11+
# Remove non-alphanumeric characters
12+
s = re.sub(pattern=r'[^a-zA-Z0-9]', repl='', string=s)
13+
14+
# Determine if s is palindrome or not
15+
len_s = len(s)
16+
17+
for i in range(len_s//2):
18+
19+
if s[i] != s[len_s - 1 - i]:
20+
return False
21+
22+
return True
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
from collections import deque, defaultdict
4+
5+
class Solution:
6+
def generateParenthesis(self, n: int) -> List[str]:
7+
"""
8+
Generate all combinations of well-formed parentheses.
9+
10+
Uses backtracking approach:
11+
- Only add '(' if we haven't used all n openings
12+
- Only add ')' if closing count < opening count
13+
- When length = 2*n, we have a valid combination
14+
15+
Time: O(4^n / sqrt(n)) - Catalan number
16+
Space: O(n) for recursion depth
17+
"""
18+
result = []
19+
20+
def backtrack(current: str, open_count: int, close_count: int):
21+
# Base case: we've used all n pairs
22+
if len(current) == 2 * n:
23+
result.append(current)
24+
return
25+
26+
# Add opening parenthesis if we haven't used all n
27+
if open_count < n:
28+
backtrack(current + '(', open_count + 1, close_count)
29+
30+
# Add closing parenthesis if it doesn't exceed opening count
31+
if close_count < open_count:
32+
backtrack(current + ')', open_count, close_count + 1)
33+
34+
backtrack('', 0, 0)
35+
return result
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
function generateParenthesis(n: number): string[] {
2+
const result: string[] = [];
3+
4+
function backtrack(current: string, openCount: number, closeCount: number): void {
5+
// Base case: we've used all n pairs
6+
if (current.length === 2 * n) {
7+
result.push(current);
8+
return;
9+
}
10+
11+
// Add opening parenthesis if we haven't used all n
12+
if (openCount < n) {
13+
backtrack(current + '(', openCount + 1, closeCount);
14+
}
15+
16+
// Add closing parenthesis if it doesn't exceed opening count
17+
if (closeCount < openCount) {
18+
backtrack(current + ')', openCount, closeCount + 1);
19+
}
20+
}
21+
22+
backtrack('', 0, 0);
23+
return result;
24+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import pytest
2+
from src.my_project.interviews.top_150_questions_round_22.ex_101_generate_parentheses import Solution
3+
4+
5+
class TestGenerateParentheses:
6+
def setup_method(self):
7+
self.solution = Solution()
8+
9+
def test_example_1(self):
10+
"""Test with n = 3"""
11+
n = 3
12+
expected = ["((()))", "(()())", "(())()", "()(())", "()()()"]
13+
result = self.solution.generateParenthesis(n)
14+
assert sorted(result) == sorted(expected)
15+
16+
def test_example_2(self):
17+
"""Test with n = 1"""
18+
n = 1
19+
expected = ["()"]
20+
result = self.solution.generateParenthesis(n)
21+
assert result == expected
22+
23+
def test_n_equals_2(self):
24+
"""Test with n = 2"""
25+
n = 2
26+
expected = ["(())", "()()"]
27+
result = self.solution.generateParenthesis(n)
28+
assert sorted(result) == sorted(expected)
29+
30+
def test_n_equals_4(self):
31+
"""Test with n = 4 - verify all are well-formed"""
32+
n = 4
33+
result = self.solution.generateParenthesis(n)
34+
35+
# Verify all results have correct length
36+
assert all(len(s) == 2 * n for s in result)
37+
38+
# Verify all are well-formed
39+
for s in result:
40+
balance = 0
41+
for char in s:
42+
if char == '(':
43+
balance += 1
44+
else:
45+
balance -= 1
46+
# Balance should never go negative
47+
assert balance >= 0
48+
# Final balance should be 0
49+
assert balance == 0
50+
51+
# For n=4, there should be 14 combinations (Catalan number C_4)
52+
assert len(result) == 14
53+
54+
def test_all_results_are_unique(self):
55+
"""Verify no duplicates in results"""
56+
n = 3
57+
result = self.solution.generateParenthesis(n)
58+
assert len(result) == len(set(result))
59+
60+
def test_all_results_are_valid(self):
61+
"""Verify all results are well-formed parentheses"""
62+
n = 3
63+
result = self.solution.generateParenthesis(n)
64+
65+
for s in result:
66+
balance = 0
67+
for char in s:
68+
if char == '(':
69+
balance += 1
70+
else:
71+
balance -= 1
72+
# At any point, closing should not exceed opening
73+
assert balance >= 0
74+
# At the end, all parentheses should be matched
75+
assert balance == 0

0 commit comments

Comments
 (0)