DEV Community

muriuki muriungi erick
muriuki muriungi erick

Posted on

Hashmap in python.

Hashmap in python.
Hashmaps are indexed data structures which are also known as hash tables. They are used to compute the index with a key into an array of slots. Hashmaps are unique and immutable. Ideally hashmaps will store key-value pairs and the key are generated using a hash function.
Hashmaps can be compared to closet having several drawers where each drawer is used to store specific clothes. These drawers are labelled with the name of clothes they store. Hashmaps makes it easier and faster to access data.
In python hashmaps are implemented using built in function called dictionary. To understand more about the application of hash map I have used this example from letcode (https://leetcode.com/problems/two-sum/description/)

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]

As we can see we have a list of values stored in a variable named nums
Also, we have a target that is the sum of two values from the list
We are supposed to find the two values in the list those add up to the target and give them as an array. This is how we can achieve this.

class Solution(object):
    def twoSum(self, nums, target):
    #initialize the hashmap to sore the values
        compliment_dict= {}
     #loop through the values in the list
        for values in range(len(nums)):
            compliment= target-nums[values]
            if compliment in compliment_dict:
                return compliment_dict[compliment],values
            compliment_dict[nums[values]] = values

Enter fullscreen mode Exit fullscreen mode

Conclusion
Here hashmap is used to store the element of an array. We iterate through the array and for each element we check for the compliment (target- current element). If the compliment exists in the hashmap it means that we have two numbers those can add up to the target.

Top comments (0)