From 24a9636b92af71bf561967ec5d91456ec0c49a6a Mon Sep 17 00:00:00 2001 From: Cabebe Date: Sat, 23 Jul 2022 15:57:15 -0700 Subject: [PATCH 1/2] adds grouped_anagrams method --- hash_practice/exercises.py | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/hash_practice/exercises.py b/hash_practice/exercises.py index 48bf95e..a36e86a 100644 --- a/hash_practice/exercises.py +++ b/hash_practice/exercises.py @@ -2,10 +2,27 @@ 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_map = {} + if not strings: + return [] + + for string in strings: + letters_in_string = ''.join(sorted(string)) + if letters_in_string in anagrams_map: + anagrams_map[letters_in_string].append(string) + else: + anagrams_map[letters_in_string] = [string] + + anagrams = [] + for item in anagrams_map.values(): + anagrams.append(item) + + return anagrams + + def top_k_frequent_elements(nums, k): """ This method will return the k most common elements From da0a75ed25a3666ca90b0b5c8f50dffaaf89b547 Mon Sep 17 00:00:00 2001 From: Cabebe Date: Sun, 24 Jul 2022 14:13:46 -0700 Subject: [PATCH 2/2] adds top_k_frequent_elements method --- hash_practice/exercises.py | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/hash_practice/exercises.py b/hash_practice/exercises.py index a36e86a..c6aedc9 100644 --- a/hash_practice/exercises.py +++ b/hash_practice/exercises.py @@ -27,10 +27,26 @@ def grouped_anagrams(strings): 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 + element_map = {} + for num in nums: + if num not in element_map: + element_map[num] = 1 + else: + element_map[num] += 1 + + most_common = [] + value_list = list(element_map.values()) + for key, value in element_map.items(): + if value == max(value_list): + most_common.append(key) + value_list.remove(value) + if len(most_common) == k: + break + + return most_common def valid_sudoku(table):