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
Expand Up @@ -54,4 +54,55 @@ def countTheNumOfKFreeSubsets(self, nums: List[int], k: int) -> int:
res *= chain_res
i = j

return res
return res


'''
Detailed Algorithm Explanation
Part 1: Why Group by num % k?
Two numbers can have a difference of exactly k only if they have the same remainder when divided by k.

Mathematical proof:

If a - b = k, then a = b + k
Therefore: a % k = (b + k) % k = b % k
Example: nums = [2, 3, 5, 8], k = 5

num | num % 5 | group
----|---------|-------
2 | 2 | Group A
3 | 3 | Group B
5 | 0 | Group C
8 | 3 | Group B


Why this matters: Elements from different groups can never differ by k, so they're independent. We can combine any subset from Group A with any subset from Group B.

Part 2: Building Chains
Within each group, we sort and find chains where consecutive elements differ by exactly k.

Example with Group B: [3, 8]

Sorted: [3, 8]
Check: 8 - 3 = 5 ✓
Chain: 3 → 8

Another example: nums = [1, 6, 11, 21], k = 5 (all have remainder 1)

Sorted: [1, 6, 11, 21]
Check: 6-1=5 ✓, 11-6=5 ✓, 21-11=10 ✗
Chains: [1 → 6 → 11], [21]


Part 3: House Robber DP - The Core Logic
For a chain like [3 → 8], we can't pick both 3 and 8 (they differ by k). This is the House Robber problem: count all subsets where we don't pick adjacent elements.

DP State Variables
take = number of valid subsets that INCLUDE the current element
skip = number of valid subsets that EXCLUDE the current element

DP Transitions
new_take = skip # To take current, we MUST have skipped previous
new_skip = take + skip # To skip current, we can take or skip previous

'''
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
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,23 @@
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='[^a-zA-Z0-9]', repl='', string=s)

# Determine if it 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,21 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

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

dic_answer = dict()

words = s.split(' ')

if len(words) != len(pattern) or len(set(words)) != len(set(pattern)):
return False
else:
for k, v in enumerate(words):
if v in dic_answer:
if dic_answer[v] != pattern[k]:
return False
else:
dic_answer[v] = pattern[k]

return True
20 changes: 20 additions & 0 deletions tests/test_150_questions_round_21/test_word_pattern_round_21.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import unittest
from src.my_project.interviews.top_150_questions_round_21\
.word_pattern import Solution

class WordPatternTestCase(unittest.TestCase):

def test_is_word_pattern(self):
solution = Solution()
output = solution.wordPattern(pattern="abba", s="dog cat cat dog")
self.assertTrue(output)

def test_is_no_word_pattern_one(self):
solution = Solution()
output = solution.wordPattern(pattern="abc", s="dog cat cat fish")
self.assertFalse(output)

def test_is_no_word_pattern_two(self):
solution = Solution()
output = solution.wordPattern(pattern="aa", s="dog cat cat fish")
self.assertFalse(output)