Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:

answer = dict()

for k, v in enumerate(nums):

if v in answer:
return [answer[v], k]
else:
answer[target - v] = k

return []





Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod
import re

class Solution:
def isPalindrome(self, s: str) -> bool:

# To lowercase
s = s.lower()

# Remove non-alphanumeric characters
s = re.sub(pattern=r'[^a-zA-Z0-9]', repl='', string=s)

# Determine if s is palindrome or not
len_s = len(s)

for i in range(len_s//2):

if s[i] != s[len_s - 1 - i]:
return False

return True
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod
from collections import deque, defaultdict

class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""
Generate all combinations of well-formed parentheses.

Uses backtracking approach:
- Only add '(' if we haven't used all n openings
- Only add ')' if closing count < opening count
- When length = 2*n, we have a valid combination

Time: O(4^n / sqrt(n)) - Catalan number
Space: O(n) for recursion depth
"""
result = []

def backtrack(current: str, open_count: int, close_count: int):
# Base case: we've used all n pairs
if len(current) == 2 * n:
result.append(current)
return

# Add opening parenthesis if we haven't used all n
if open_count < n:
backtrack(current + '(', open_count + 1, close_count)

# Add closing parenthesis if it doesn't exceed opening count
if close_count < open_count:
backtrack(current + ')', open_count, close_count + 1)

backtrack('', 0, 0)
return result
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
function generateParenthesis(n: number): string[] {
const result: string[] = [];

function backtrack(current: string, openCount: number, closeCount: number): void {
// Base case: we've used all n pairs
if (current.length === 2 * n) {
result.push(current);
return;
}

// Add opening parenthesis if we haven't used all n
if (openCount < n) {
backtrack(current + '(', openCount + 1, closeCount);
}

// Add closing parenthesis if it doesn't exceed opening count
if (closeCount < openCount) {
backtrack(current + ')', openCount, closeCount + 1);
}
}

backtrack('', 0, 0);
return result;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import pytest
from src.my_project.interviews.top_150_questions_round_22.ex_101_generate_parentheses import Solution


class TestGenerateParentheses:
def setup_method(self):
self.solution = Solution()

def test_example_1(self):
"""Test with n = 3"""
n = 3
expected = ["((()))", "(()())", "(())()", "()(())", "()()()"]
result = self.solution.generateParenthesis(n)
assert sorted(result) == sorted(expected)

def test_example_2(self):
"""Test with n = 1"""
n = 1
expected = ["()"]
result = self.solution.generateParenthesis(n)
assert result == expected

def test_n_equals_2(self):
"""Test with n = 2"""
n = 2
expected = ["(())", "()()"]
result = self.solution.generateParenthesis(n)
assert sorted(result) == sorted(expected)

def test_n_equals_4(self):
"""Test with n = 4 - verify all are well-formed"""
n = 4
result = self.solution.generateParenthesis(n)

# Verify all results have correct length
assert all(len(s) == 2 * n for s in result)

# Verify all are well-formed
for s in result:
balance = 0
for char in s:
if char == '(':
balance += 1
else:
balance -= 1
# Balance should never go negative
assert balance >= 0
# Final balance should be 0
assert balance == 0

# For n=4, there should be 14 combinations (Catalan number C_4)
assert len(result) == 14

def test_all_results_are_unique(self):
"""Verify no duplicates in results"""
n = 3
result = self.solution.generateParenthesis(n)
assert len(result) == len(set(result))

def test_all_results_are_valid(self):
"""Verify all results are well-formed parentheses"""
n = 3
result = self.solution.generateParenthesis(n)

for s in result:
balance = 0
for char in s:
if char == '(':
balance += 1
else:
balance -= 1
# At any point, closing should not exceed opening
assert balance >= 0
# At the end, all parentheses should be matched
assert balance == 0
Loading