From c08140a2309a15f83072b50b8098d5607d0e8755 Mon Sep 17 00:00:00 2001 From: marielaxcruz Date: Mon, 17 Jan 2022 20:05:42 -0800 Subject: [PATCH] Pass required tests --- hash_practice/exercises.py | 46 +++++++++++++++++++++++---- tests/test_top_k_frequent_elements.py | 2 +- 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/hash_practice/exercises.py b/hash_practice/exercises.py index 48bf95e..530ba4c 100644 --- a/hash_practice/exercises.py +++ b/hash_practice/exercises.py @@ -1,20 +1,52 @@ -def grouped_anagrams(strings): +def grouped_anagrams(d1): """ This method will return an array of arrays. Each subarray will have strings which are anagrams of each other Time Complexity: ? Space Complexity: ? """ - pass + # empty dictionary for anagrams together + dict = {} + + # traversal + for val in d1: + # sorts list + key = ''.join(sorted(val)) + + if key in dict.keys(): + dict[key].append(val) + else: + dict[key] = [] + dict[key].append(val) + + # traverse dictionary and join keys together + result = [] + for key,value in dict.items(): + # result = result + ' '.join(value) + ' ' + result.append(value) + return result -def top_k_frequent_elements(nums, k): +def top_k_frequent_elements(numbers, 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 - + freq_map = {} + if numbers == []: + return numbers + for i in numbers: + if i in freq_map: + freq_map[i] += 1 + elif i not in freq_map: + freq_map[i] = 1 + + new_list = [] + for i in range(k): + highest_value = max(freq_map, key=freq_map.get) + new_list.append(highest_value) + freq_map.pop(highest_value) + return new_list def valid_sudoku(table): """ This method will return the true if the table is still diff --git a/tests/test_top_k_frequent_elements.py b/tests/test_top_k_frequent_elements.py index 9e653cf..a44ed2c 100644 --- a/tests/test_top_k_frequent_elements.py +++ b/tests/test_top_k_frequent_elements.py @@ -7,7 +7,7 @@ def test_it_works_with_example_1(): k = 2 # Act - answer = top_k_frequent_elements(nums=numbers, k=k) + answer = top_k_frequent_elements(numbers=numbers, k=k) # Assert answer.sort()