Skip to content
Open

Hashing #2265

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
26 changes: 26 additions & 0 deletions anagrams.py
Original file line number Diff line number Diff line change
@@ -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())
22 changes: 22 additions & 0 deletions isomorphic.py
Original file line number Diff line number Diff line change
@@ -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
28 changes: 28 additions & 0 deletions wordPattern.py
Original file line number Diff line number Diff line change
@@ -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