Finding the Intersection of Two Arrays Using a Hash Map
Problem Statement
Given two integer arrays, implement a function to compute their intersection. The result should contain only unique elements, and the order of the output is not important.
Python Solution
from typing import List
class ArrayIntersection:
def find_intersection(self, arr1: List[int], arr2: List[int]) -> List[int]:
# Initialize a dictionary to track elements from the first array
element_counter = {}
# Populate the dictionary with elements from arr1
for value in arr1:
# Increment count for each occurrence, defaulting to 0 if not present
element_counter[value] = element_counter.get(value, 0) + 1
# Use a set to store intersecting elements without duplicates
intersection_set = set()
# Check each element in arr2 against the dictionary
for value in arr2:
if value in element_counter:
intersection_set.add(value)
# Remove the element to prevent duplicate matches
del element_counter[value]
# Convert the set to a list for the final result
return list(intersection_set)
Solution Breakdown
This aproach uses a hash map (dictionary) to efficiently determine common elements between two arrays. The process is as follows:
-
Hash Map Construction:
- A dictionary named
element_counteris created to store elements from the first array (arr1). - Each element from
arr1serves as a key, with its value representing the count of occurrences. Thegetmethod is used to safely increment the count, initializing it to 0 if the key is absent.
- A dictionary named
-
Intersection Identification:
- A set called
intersection_setis initialized to hold the intersection results, ensuring uniqueness. - The second array (
arr2) is traversed. For each element, if it exists as a key inelement_counter, it is added tointersection_set. - The element is then removed from
element_counterusingdelto avoid redundant additions.
- A set called
-
Result Preparation:
- The set is converted to a list and returned as the final output.
Key Code Explanation
The line element_counter[value] = element_counter.get(value, 0) + 1 is central to building the hash map. Here’s a step-by-step interpretation:
element_counter.get(value, 0)retrieves the current count forvaluefrom the dictionary. Ifvalueis not found, it returns the default value0.- Adding
1increments this count, accounting for the current occurrence ofvalueinarr1. - The updated count is then assigned back to
element_counter[value], effectively tracking the frequency of each element.
This concise sttaement combines checking to an existing key, handling missing keys, and updating the count in a single operation.