Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 41 additions & 2 deletions hash_practice/exercises.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,54 @@ def grouped_anagrams(strings):
Time Complexity: ?
Space Complexity: ?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For both this and the top-K problem, complexity calculations are missing.

"""
pass
anagrams = {}
for string in strings:
sorted_string = sorted(string)
joined_string = ''.join(sorted_string)
if joined_string in anagrams:
anagrams[joined_string].append(string)
else:
anagrams[joined_string] = [string]
anagram_list = []
for key in anagrams.keys():
anagram_list.append(anagrams[key])
return anagram_list

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: ?
"""
pass
nums_dict = {}
for i in range(len(nums)):
if nums[i] in nums_dict:
nums_dict[nums[i]] += 1
else:
nums_dict[nums[i]] = 1

frequency_dict={}
max_value = 0
for key, value in nums_dict.items():
if frequency_dict.get(value):
frequency_dict[value].append(key)
else:
frequency_dict[value] = [key]

if value > max_value:
max_value = value
final_list = []
for i in range(k):
frequency_nums = frequency_dict.get(max_value - i)
if frequency_nums:
check_next = 0
for num in frequency_nums:
if check_next + i < k:
final_list.append(num)
else:
break
check_next += 1

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately this method of limiting the result to k values has the possibility of returning more than k values, particularly if there are ties. For example, given [1, 1, 1, 2, 2, 2, 3, 3, 4] with k = 2, [1, 2, 3] will be the returned result. Essentially, when i is zero both 1 and 2 will be added to final_list, then 3 will be added on the next iteration when i is one.

However, as our problem statement underspecifies how to handle ties, I do not think it's fair to ding you for this, I just wanted to call it to your attention.

return final_list


def valid_sudoku(table):
Expand Down