Skip to content
Open
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
53 changes: 53 additions & 0 deletions problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Time Complexity: O(n.k), where n is the number of strings and k is the maximum length of a string, since we compute the hash by iterating each character.
# Space Complexity: O(n.k), to store the grouped anagrams in the hashmap and the output list.
# Approach: Assign each character a unique prime number and compute the product for each string to form a unique hash, then use a hashmap to group strings that share the same hash
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
# smap = defaultdict(list)
smap = {}
for i in strs:

hash_ = self.getHash(i)
if hash_ in smap:
smap[hash_].append(i)
else:
smap[hash_] = [i]

return list(smap.values())

def getHash(self, str: str) -> float:

primes = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
]

hash = 1
for c in str:
hash *= primes[ord(c) - ord("a")]

return hash
23 changes: 23 additions & 0 deletions problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Time Complexity: O(n), where n is the length of the string
# Space Complexity: O(n), for storing character mappings in the hashmap and the used set in the worst case.
# Approach: Use a hashmap to map each character from s to t and a set to ensure no two characters from s map to the same character in t, checking consistency in one pass.
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
smap={}
used=set()

for i in range(len(s)):

sChar = s[i]
tChar = t[i]

if sChar in smap:
if smap[sChar]!=tChar:
return False
else:
if tChar in used:
return False
smap[sChar]=tChar
used.add(tChar)
print(smap,used)
return True
31 changes: 31 additions & 0 deletions problem3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Time Complexity: O(n), where n is the number of words in s
# Space Complexity:O(n), for storing mappings in the hashmap smap and the used set
# Approach: Split the string into words, then use a hashmap to map each pattern character to a word and a set to ensure no two characters map to the same word,

class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
smap={}
s=s.split()
# print(s)
used=set()
if len(pattern)!=len(s):
return False
for i in range(len(s)):
# print(pattern[i], s[i])
if pattern[i] in smap:
if smap[pattern[i]]!=s[i]:
return False
else:
if s[i] in used:
return False
smap[pattern[i]]=s[i]
used.add(s[i])

return True