HashMap is a data structure that stores data in the form of Key-Value. Its main advantage is that data can be searched and updated very quickly, because the data is located using the hashcode of the key. So anywhere where data needs to be searched quickly, HashMap is very useful.
Why use?
- For fast search, insert and delete work
- To avoid keeping duplicate data with the same key, the advantage of value update
- Database, caching, counting, frequency tracking
Where is it used?
- Getting information by user ID
- Searching by name by product code
- In cache mechanism
- Array-mapping of algorithms (such as LeetCode Two Sum)
Small Python code example (Two Sum Problem):
nums = [2, 7, 11, 15]
target = 9
def twoSum(nums, target):
hashmap = {}
for i, num in enumerate(nums):
complement = target - num
if complement in hashmap:
return [hashmap[complement], i]
hashmap[num] = i
print(twoSum(nums, target)) # Output: [0, 1]
Here we search for two numbers from the nums array whose sum is equal to target. We quickly get the index of those two numbers using hashmap in the code.
This code is explained below -
1. def twoSum(nums, target):
I define a function that takes a list of numbers (nums) and a target number.
2. hashmap = {}
I create a simple dictionary (HashMap), where the number will be the number and the value will be its index.
3. for i, num in enumerate(nums):
I loop through each number in the nums list and its index.
4. complement = target - num
I want a number that will be the target after subtracting the current number from the target.
5. if complement in hashmap:
I check whether the required number is in the hashmap or not.
6. return [hashmap[complement], i]
If it is, I return the index of the two numbers.
7. hashmap[num] = i
If not, then we add the current number and its index to the hashmap.
In this way, we can quickly find the positions of two numbers whose sum is equal to the target by running the loop once.
HashMap is a smart way to find data quickly, storing data as key-value pairs. Using it, searches, inserts, updates, everything is much faster. So whenever fast data access is necessary, HashMap is the best companion! 🚀
Top comments (0)