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
54 changes: 46 additions & 8 deletions hash_practice/exercises.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,57 @@
# Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
# Output:
# [
# ["ate","eat","tea"],
# ["nat","tan"],
# ["bat"]
# ]

Choose a reason for hiding this comment

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

As a style thing, you'll usually want to remove comments like this that are not really related to explaining why the code is designed a certain way.


def sortString(string):
sorted_letters = sorted(string)
sorted_string = "".join(sorted_letters)
return sorted_string

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: ?
Each sub-array will have strings which are anagrams of each other
Time Complexity: O(n)
Space Complexity: O(n)
"""
pass
temp = {}
array_words = []

for word in strings:
sorted_word = sortString(word)
if sorted_word in temp:
temp[sorted_word].append(word)
else:
temp[sorted_word] = [word]

for key in temp:
array_words.append(temp[key])
return array_words



# Input: nums = [1,1,1,2,2,3], k = 2
# Output: [1,2]

Choose a reason for hiding this comment

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

Same as above, you can probably remove comments like these after they've helped you write your code.


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: ?
In the case of a tie it will select the first occurring element.
Time Complexity: O(n)

Choose a reason for hiding this comment

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

Don't forget to account for the call to sorted, which takes O(n * log(n)) time, and thus dominates the O(n) part of this algorithm giving a final time complexity of O(n * log(n)).

Space Complexity: O(n)
"""
pass
hash_table = {}
for num in nums:
if num in hash_table:
hash_table[num] += 1
else:
hash_table[num] = 1

# get keys with highest count based on k
sorted_keys = sorted(hash_table.keys(), key=hash_table.get, reverse=True)
return sorted_keys[0:k]


def valid_sudoku(table):
Expand Down