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: 37 additions & 6 deletions hash_practice/exercises.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,49 @@
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 = {}
for word in strings:
alphabet = [0] * 26
for letter in word:
alphabet[ord(letter.lower()) - ord("a")] += 1
if tuple(alphabet) in anagrams:
anagrams[tuple(alphabet)].append(word)
else:
anagrams[tuple(alphabet)] = [word]

return_list = []
for k, v in anagrams.items():
return_list.append(v)
return return_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: ?
Time Complexity: O(n)

Choose a reason for hiding this comment

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

Note that max may end up going through every key-value pair in element_dict, of which there may be O(n) pairs, one for every number in nums. It may do this up to k times so the time complexity here is O(n + nk), of which that last part dominates for O(nk).

Space Complexity: O(n)
"""
pass
if len(nums) == 0:
return []

count = []
element_dict = {}

for elem in nums:
if elem in element_dict:
element_dict[elem] += 1
else:
element_dict[elem] = 1

while len(count) < k:
highest_key = max(element_dict, key=element_dict.get)
count.append(highest_key)

del element_dict[highest_key]

return count


def valid_sudoku(table):
Expand Down