Hashmaps are dynamic data structures that efficiently store and manage key-value pairs using a technique called hashing. In a hashmap, each key is processed through a hash function, which generates a unique address in memory for storing its corresponding value. This allows for constant O(n) access to elements, regardless of the size of the data set, making hashmaps ideal for applications that require rapid lookup, insertion, and deletion operations.
Identifying the need to use a hashmap is essential when you encounter problems that require efficient mappings of key-value pairs. Hashmaps excel in tasks such as counting frequencies, like determining the number of occurrences of each character in a string. Or grouping items by attributes, such as classifying words by their starting letter. Additionally, hashmaps are invaluable for quickly finding pairs that satisfy certain conditions, such as two numbers that add up to a specific target in a list, by storing and checking for the necessary complements efficiently. This capability significantly speeds up solutions
Now Let’s go through this Example Problem: Two Sum
We are given an array of integers nums
and an integer target
. The goal is to return the indices of two numbers in the array such that they add up to the target
. Each input has exactly one solution, and you cannot use the same element twice. The order of the indices does not matter.
i
, we can check every other number j
to see if nums[i] + nums[j] == target
.target - nums[i]
) in a hash map. The complement is the number we need to find in the array to add up to the target with the current number.[3, 3]
).[1, 2]
and target = 3
).[2, 2, 2, 2]
).num_to_index
to store the complement of the numbers we have seen.nums
with an index i
:
complement = target - nums[i]
.complement
is already in num_to_index
, return the indices [num_to_index[complement], i]
since we found the pair.num_to_index[nums[i]] = i
.class Solution(object):
def twoSum(self, nums, target):
num_to_index = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_to_index:
return [num_to_index[complement], i]
num_to_index[num] = i
num_to_index
to store numbers and their corresponding indices as we iterate through the array.num
at index i
in the array nums
, we calculate its complement as target - num
.num_to_index
.
target
, so we return their indices: [num_to_index[complement], i]
.num
and its index i
in num_to_index
.