hash map / set Flashcards

1
Q

find the difference of two arrays: intuition

A

You want to find the elements that are on only one list, not on both.

The unordered sets act like hash tables, allowing for quick checks to see if a specific marble exists in the other set.

We iterate through each element in one set, checking if it’s present in the other set. If not, it’s unique and gets added to the result.

Return the list ans

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

find the difference of two arrays: code

A

def findDifference(nums1: List[int], nums2: List[int]) -> List[List[int]]:
set1, set2, result1, result2 = set(nums1), set(nums2), [], []

for i in nums1: 
    if i not in set2:
        result1.append(i)
    
for i in nums2:
    if i not in set1:
        result2.append(i)

return [list(set(result1)), list(set(result2))]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

unique number of occurrences: intuition

A

If we have the frequencies of all elements, we can put them in a hash set. If the size of the hash set is equal to the number of elements, it implies that the frequencies are unique. Hence, we will find the frequencies of all elements in a hash map and then put them in a hash set.

Algorithm:
Store the frequencies of elements in the array arr in the hash map freq.

Iterate over the hash map freq and insert the frequencies of all unique elements of array arr in the hash set freqSet.

Return true if the size of hash set freqSet is equal to the size of hash map freq, otherwise return false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

unique number of occurrences: code

A

def uniqueOccurrences(arr: List[int]) -> bool:
freq = {}
for x in arr:
freq[x] = freq.get(x, 0) + 1

return len(freq) == len(set(freq.values()))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

determine if two strings are close: intuition

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

determine if two strings are close: code

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

equal row and column pairs: intuition

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

equal row and column pairs: code

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly