From 785478ac23f1ed468e89f79c5886d8c489886077 Mon Sep 17 00:00:00 2001 From: Drew Taylor Date: Fri, 21 Jan 2022 00:38:17 -0800 Subject: [PATCH] All finished --- hash_practice/exercises.py | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/hash_practice/exercises.py b/hash_practice/exercises.py index 48bf95e..a58a4a3 100644 --- a/hash_practice/exercises.py +++ b/hash_practice/exercises.py @@ -2,18 +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 log n) """ - pass + letters_hash = {} + + for word in strings: + anagram_sorted = "".join(sorted(word)) + if anagram_sorted in letters_hash: + letters_hash[anagram_sorted].append(word) + else: + letters_hash[anagram_sorted] = [word] + + return list(letters_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 + highest_k_hash = {} + if nums == []: + return nums + + for num in nums: + if num in highest_k_hash: + highest_k_hash[num] += 1 + else: + highest_k_hash[num] = 1 + + sorted_k_values = [] + for i in range(k): + highest_freq_value = max(highest_k_hash, key=highest_k_hash.get) + sorted_k_values.append(highest_freq_value) + highest_k_hash.pop(highest_freq_value) + + return sorted_k_values def valid_sudoku(table):