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
40 changes: 34 additions & 6 deletions hash_practice/exercises.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,46 @@
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^2)? The fucntion only loops through the length of strings for

Choose a reason for hiding this comment

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

⏱ Sorting is an O(n) operation, however if we assume all strings are valid english words, we can say this is an O(1) operation because n will never be very large.

Therefore you just have the for loop through the elements of strings which would make this O(n)

the number of letters in each string?
Space Complexity: O(n)? Theres only 2 varaibles being stored...sortedWord and anagramsHash?

Choose a reason for hiding this comment

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

🪐 Yes! anagramsHash can have at most n elements where n is the length of strings. Overall the combined length of the values will also be n elements.

"""
pass
anagramsHash = {}
for string in strings:
sortedWord = "".join(sorted(string))
if sortedWord in anagramsHash:
anagramsHash[sortedWord].append(string)
else:
anagramsHash[sortedWord] = [string]
return list(anagramsHash.values())


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^2)?

Choose a reason for hiding this comment

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

Space complexity would be O(n). finalList will be of length k which can never be greater than the length of nums. freqHash will have at most n key value pairs as well, where the values are all integers.

"""
pass
freqHash = {}
finalList = []

if len(nums) == 0:
return finalList
for number in nums:
if number not in freqHash:
freqHash[number] = 0
else:
freqHash[number] += 1

count = 1

while count <= k:
finalList.append(sorted(freqHash, key=freqHash.get)[-count])
count += 1
return finalList





def valid_sudoku(table):
Expand Down