From 4413729f6e8582aa1cdd24dd363be86b70f6db11 Mon Sep 17 00:00:00 2001 From: Hannah Lumapas Date: Mon, 17 Jan 2022 16:05:59 -0500 Subject: [PATCH] passes required tests --- hash_practice/exercises.py | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/hash_practice/exercises.py b/hash_practice/exercises.py index 48bf95e..f400bbd 100644 --- a/hash_practice/exercises.py +++ b/hash_practice/exercises.py @@ -2,19 +2,43 @@ 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(n) + Space Complexity: O(n) """ - pass + anagrams_hash = {} + + for word in strings: + sorted_word = "".join(sorted(word)) + if sorted_word in anagrams_hash: + anagrams_hash[sorted_word].append(word) + else: + anagrams_hash[sorted_word] = [word] + + return list(anagrams_hash.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: O(n) + Space Complexity: O(n) """ - pass + frequency_hash = {} + if nums == []: + return nums + + for num in nums: + if num in frequency_hash: + frequency_hash[num] += 1 + else: + frequency_hash[num] = 1 + return_list = [] + for i in range(k): + highest_value = max(frequency_hash, key=frequency_hash.get) + return_list.append(highest_value) + frequency_hash.pop(highest_value) + + return return_list def valid_sudoku(table): """ This method will return the true if the table is still @@ -26,4 +50,3 @@ def valid_sudoku(table): Space Complexity: ? """ pass -