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
20 changes: 20 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#Group Anagrams
# create a map to group the anagrams
# the key will be the frequency of the alphabets as in anagrams character frequency are same
# for saving the frequency use the 26 length array, and once you have the freq convert to tupple and use it as key
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
mapOfCharFreq = {}
for string in strs:
charArr = [0]*26
for char in string:
index = ord(char) - 97
charArr[index]+=1
charTupple = tuple(charArr)
if charTupple in mapOfCharFreq:
mapOfCharFreq[charTupple].append(string)
else:
mapOfCharFreq[charTupple] = [string]
return list(mapOfCharFreq.values())
print(groupAnagrams(["eat","tea","tan","ate","nat","bat"]))

24 changes: 24 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Isomorphic Strings
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
#create map of char in s to t when validating from s to t, to validate same char is not mapped to 2 different char. If yes it's not isomorphic
#rplicate same from t to s
# for runtiime optimization do it in 1 pass

sToTMap = {}
tToSMap = {}
for i in range(0,len(s)):
sChar = s[i]
tCHar = t[i]
if sChar in sToTMap:
if sToTMap[sChar] != tCHar:
return False
else:
sToTMap[sChar] = tCHar

if tCHar in tToSMap:
if tToSMap[tCHar] != sChar:
return False
else:
tToSMap[tCHar] = sChar
return True
27 changes: 27 additions & 0 deletions Problem3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Word Pattern

# similar to isopmorphic, here characters in patterns are isomorphic to the str. So maintain two way map and validate mapping remains consistent
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
lengthPattern = len(pattern)
arrayS = s.split(" ")
lengthS = len(arrayS)
if lengthS != lengthPattern:
return False
charToStrMap = {}
strToCharMap = {}
for i in range(0,lengthPattern):
key = pattern[i]
if key in charToStrMap:
if charToStrMap[key] != arrayS[i]:
return False
else:
charToStrMap[key] = arrayS[i]

key = arrayS[i]
if key in strToCharMap:
if strToCharMap[key] != pattern[i]:
return False
else:
strToCharMap[key] = pattern[i]
return True