diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..dfc30586 --- /dev/null +++ b/Problem1.py @@ -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"])) + diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..1b67801f --- /dev/null +++ b/Problem2.py @@ -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 diff --git a/Problem3.py b/Problem3.py new file mode 100644 index 00000000..5f8750d2 --- /dev/null +++ b/Problem3.py @@ -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 \ No newline at end of file