From 74e0207bf8f468defac63df6713eb39fac8c7ab1 Mon Sep 17 00:00:00 2001 From: Mary Tian Date: Wed, 27 Jul 2022 20:08:44 -0600 Subject: [PATCH] Updated first two exercises. --- hash_practice/exercises.py | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/hash_practice/exercises.py b/hash_practice/exercises.py index 48bf95e..b1a49d6 100644 --- a/hash_practice/exercises.py +++ b/hash_practice/exercises.py @@ -2,18 +2,40 @@ def grouped_anagrams(strings): """ This method will return an array of arrays. Each subarray will have strings which are anagrams of each other - Time Complexity: ? - Space Complexity: ? + Time Complexity: O(nlogn)? Not sure on this + Space Complexity: 0(n) """ - pass + anagrams_dict = {} + + for word in strings: + sorted_string = ''.join(sorted(word)) + + if sorted_string in anagrams_dict: + anagrams_dict[sorted_string].append(word) + else: + anagrams_dict[sorted_string] = [word] + + return list(anagrams_dict.values()) def top_k_frequent_elements(nums, k): """ This method will return the k most common elements In the case of a tie it will select the first occuring element. - Time Complexity: ? - Space Complexity: ? + Time Complexity: 0(n) + Space Complexity: 0(n) """ - pass + nums_dict = {} + + if not nums: + return [] + + for num in nums: + if num in nums_dict: + nums_dict[num] += 1 + else: + nums_dict[num] = 1 + + most_common_list = sorted(nums_dict, key=nums_dict.get, reverse=True) + return most_common_list[:k] def valid_sudoku(table):