'TwoSums code Python (Locating Indexes of Sum Values)

Could someone please explain the lines of the following code? I am having difficulty visualizing how the hash table/map stores the values. I am also confused as to how return [prevMap[diff],i] returns the values of the indexes which correspond to the sum.

Code

List=[2,4,5,6]

target=6


class Solution:

    def twosums(self, nums, target):
        
        prevMap={} # val: index 
        
        for i, n in enumerate(nums): # key and value insertion ? 
            diff=target-n # 
            
            if diff in prevMap:
                return [prevMap[diff],i]
            prevMap[n]=i

#N=Solution() 

print(Solution().twosums(List, target))


Solution 1:[1]

Some words about dict

Let's imagine that we are bosses of a big company. We want to analyze our incomes for past years. For that we need to be able to name a year to computer and receive the income for that year in response. The structure good for such a purpose is dict (you are calling it "map"). The incomes information can be programmed like this:

incomes = {
    2010: "$100.000",
    2011: "$150.000",
    ...
    2020: "$750.000",
    2021: "$1.000.000"
}

If you want to know the income for year 2020, you can simply type incomes[2020].

Technically, dict just stores key: value pairs. In the example above keys are years and values are incomes.

Note, that there are some restrictions:

  1. Each key should be unique. It's not possible map to store two pairs key_1: value_1 and key_2: value_2 where key_1 is equal (it's not the most appropriate word here, but for simplicity let's say "equal") to key_2.
  2. Each key should be hashable: it should provide __hash__ method and be comparable (it should provide __eq__ or __cmp__ methods). Note that in-built mutable objects (such as list) are not hashable. Checkout Python glossary for further details.

Your case

  • prevMap is a dict which will store number from nums: it's index pairs.
  • enumerate returns a generator of (index, value) tuples. In your case it means that n is a number from nums and i is an index of n in nums.
  • diff is a number which we can add to n to get target.
  • The line prevMap[i] = n is simply adds pair n: i to prevMap (if there where a pair n: another_i this pair will be overwritten by n: i). It allows us to remember previous values of n and corresponding indexes.
  • Expression diff in prevMap returns True iff there is a key diff in prevMap. If it is, it means that there is a number in nums which sums up to target with n and we can get its index by typing prevMap[diff].

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1