diff --git a/problem1.py b/problem1.py new file mode 100644 index 00000000..f1c69f19 --- /dev/null +++ b/problem1.py @@ -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 diff --git a/problem2.py b/problem2.py new file mode 100644 index 00000000..2a7387db --- /dev/null +++ b/problem2.py @@ -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 diff --git a/problem3.py b/problem3.py new file mode 100644 index 00000000..7949f5b8 --- /dev/null +++ b/problem3.py @@ -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 + + + + + + + \ No newline at end of file