Image
LOADING
Innovative IT Solutions for Businesses of All Sizes

ARTICLE

Image
May 5 2023

Two Sum Solution — [Leetcode — Hashmap]

Image
Tea Cup
Go To Original Article

Two Sum Solution — [Leetcode — Hashmap]

Photo by Markus Spiske on Unsplash

Solution of two sum Leetcode problem in python

Two Sum — LeetCode

from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
values = {}
for idx, value in enumerate(nums):
if target - value in values:
return [values[target - value], idx]
else:
values[value] = idx

Explanation

values = {}

Create an empty dictionary called values. This dictionary will store the numbers from the input list along with their indices.

for idx, value in enumerate(nums):

Iterate over the input list nums using the enumerate function. This function returns a tuple containing the index of the current element and the element itself.

if target - value in values:
return [values[target - value], idx]

Check if the difference between the target value and the current value is in the values dictionary. If it is, that means there exists a pair of numbers that add up to the target value. Return a list containing the indices of these two numbers, which are stored in the values dictionary.

else:
values[value] = idx

If the difference between the target value and the current value is not in the values dictionary, store the value as a key in the values dictionary, and its corresponding index idx as the value for that key. This is done so that when we encounter a number later on in the list that can add up with the current number to the target, we can easily retrieve its index using the values dictionary.