diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..cb4748bd --- /dev/null +++ b/Problem1.py @@ -0,0 +1,25 @@ +# https://leetcode.com/problems/group-anagrams/ + +# Time Complexity : O(m*n) +# Space Complexity : O(m*n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No + +# Your code here along with comments explaining your approach in three sentences only +# Approach: +# The problem statement asks for grouping of anagrams and return a list as the result. This solution focuses on maintaining +# a count array of size 26 for every string you encounter. The count array will have the frequency of each characters in the +# current string. Using the ASCII comparison we are placing the alphabets a-z to start from 0th index (ord(c) - ord("a")). +# We are maintaining a hashmap with key being the count array and the value being the list with all the anagrams + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + my_dict = defaultdict(list) + + for s in strs: + count = [0] * 26 + for c in s: + count[ord(c) - ord("a")] += 1 + my_dict[tuple(count)].append(s) + + return list(my_dict.values()) \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..d4dff228 --- /dev/null +++ b/Problem2.py @@ -0,0 +1,30 @@ +# https://leetcode.com/problems/isomorphic-strings/ + +# Time Complexity : O(n) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : Yes +# Any problem you faced while coding this : No + +# Your code here along with comments explaining your approach in three sentences only +# Approach: +# Two strings 's' and 't' are Isomorphic if we are able to retrieve string 't' by replacing every char in string 's' +# with the respective mapping that exists and viceversa. The mapping needs to be valid both ways. This can be solved by maintaining +# two hashmaps. One hashmap to maintain the mapping from 's' to 't' and another to maintain mapping from 't' to 's'. We will be checking +# if a mapping already exists for the current character in the the hashmap for 's' and also see if there is a mapping that exists from 't' to 's'. + +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + + smap = {} + tmap = {} + i, j = 0, 0 + + for i, j in zip(s, t): + if i not in smap and j not in tmap: + smap[i] = j + tmap[j] = i + elif (i not in smap and tmap[j]) or (j not in tmap and smap[i]): + return False + elif (i in smap or j in tmap) and (smap[i] != j or tmap[j] != i): + return False + return True \ No newline at end of file