diff --git a/anagrams.py b/anagrams.py new file mode 100644 index 00000000..44299037 --- /dev/null +++ b/anagrams.py @@ -0,0 +1,26 @@ +# Time Complexity : O(N * K) +# Space Complexity : O(N) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach: Use prime-number hashing to uniquely represent each word. +# Group words by this key and return all hashmap values. + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + h_map = {} + 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] + + def getCode(s): + res = 1 + for ch in s: + res *= primes[ord(ch) - ord('a')] + return res + + for word in strs: + idx = getCode(word) + if idx not in h_map: + h_map[idx] = [word] + else: + h_map[idx].append(word) + + return list(h_map.values()) diff --git a/isomorphic.py b/isomorphic.py new file mode 100644 index 00000000..0f8eee30 --- /dev/null +++ b/isomorphic.py @@ -0,0 +1,22 @@ +# Time Complexity : O(n) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach: Use a hashmap to store character mappings from string `s` to `t`. +# Iterate through both strings once and validate the one-to-one mapping. + +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + key_map = {} + value_set = set() + + for i in range(len(s)): + if s[i] not in key_map: + if t[i] in value_set: + return False + key_map[s[i]] = t[i] + value_set.add(t[i]) + else: + if key_map[s[i]] != t[i]: + return False + return True diff --git a/wordPattern.py b/wordPattern.py new file mode 100644 index 00000000..b1ebbf02 --- /dev/null +++ b/wordPattern.py @@ -0,0 +1,28 @@ +# Time Complexity : O(n) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No +# Approach: +# Split the input string into words. Use a hashmap to map each character in `pattern` to a word. +# Iterate once through the pattern and validate. + +class Solution: + def wordPattern(self, pattern: str, s: str) -> bool: + words = s.split() + if len(words) != len(pattern): + return False + + h_map = {} + used = set() + + for i in range(len(pattern)): + if pattern[i] not in h_map: + if words[i] in used: + return False + h_map[pattern[i]] = words[i] + used.add(words[i]) + else: + if h_map[pattern[i]] != words[i]: + return False + + return True