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
22 changes: 22 additions & 0 deletions group_anagrams.py
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions isomorphic_srtings.py
Original file line number Diff line number Diff line change
@@ -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
25 changes: 25 additions & 0 deletions word_pattern.py
Original file line number Diff line number Diff line change
@@ -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