diff --git a/group_anagrams.py b/group_anagrams.py new file mode 100644 index 00000000..ea4c61ac --- /dev/null +++ b/group_anagrams.py @@ -0,0 +1,22 @@ +""" +time - o(n) +space - o(n) +we take each word, sort its letters and store it as the key, and the word becomes +a value in dictionary +""" + +from typing import List + + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + anagram_map = {} + for string in strs: + string_tuple = tuple(sorted(list(string))) + if not string_tuple in anagram_map: + anagram_map[string_tuple] = [] + anagram_map[string_tuple].append(string) + result = [] + for _, value in anagram_map.items(): + result.append(value) + return result diff --git a/isomorphic_srtings.py b/isomorphic_srtings.py new file mode 100644 index 00000000..b728d1aa --- /dev/null +++ b/isomorphic_srtings.py @@ -0,0 +1,21 @@ +""" +time - o(n) +space - o(n) +we map two characters to each other in two separate dicts +if the pattern does not repeat we return false +""" + + +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + s_map = {} + t_map = {} + for i in range(len(s)): + if s[i] not in s_map and t[i] not in t_map: + s_map[s[i]] = t[i] + t_map[t[i]] = s[i] + elif s_map.get(s[i]) != t[i] or t_map.get(t[i]) != s[i]: + return False + return True diff --git a/word_pattern.py b/word_pattern.py new file mode 100644 index 00000000..8057fbac --- /dev/null +++ b/word_pattern.py @@ -0,0 +1,25 @@ +""" +time - o(n) +space - o(n) +same as isomorphic string we link each word and store them as key value +pairs in two dictionaries (with key and value interchanged) and if the pattern +does not repeat return false +""" + + +class Solution: + def wordPattern(self, pattern: str, s: str) -> bool: + s_list = s.split() + if len(s_list) != len(pattern): + return False + s_map = {} + c_map = {} + for i in range(len(pattern)): + if pattern[i] not in s_map and s_list[i] not in c_map: + s_map[pattern[i]] = s_list[i] + c_map[s_list[i]] = pattern[i] + elif ( + s_map.get(pattern[i]) != s_list[i] or c_map.get(s_list[i]) != pattern[i] + ): + return False + return True