hash map / set Flashcards
find the difference of two arrays: intuition
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
find the difference of two arrays: code
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))]
unique number of occurrences: intuition
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.
unique number of occurrences: code
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()))
determine if two strings are close: intuition
determine if two strings are close: code
equal row and column pairs: intuition
equal row and column pairs: code