Skip to content

LeetCode

Two Sum

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:

Input: nums = [2,7,11,15], target = 9

Output: [0,1]

Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Solution Explanation

This is the first problem in Leetcode. The approach for solving this problem will be, to start from first number of the list, get a complement value by subtracting it from the target and check where that value belongs in the list.

We can use a hashmap for tracking indexes of the items so we won't have to iterate through the list over and over again as we look for complement value index.

solution.py
def twoSum(nums: List[int], target: int) -> List[int]:
  hashMap = {}
  n = len(nums)

  for i in range(n):
      complement = target - nums[i]
      if complement in hashMap:
          return [hashMap[complement], i]
      hashMap[nums[i]] = i
  return []

That's it for this problem, one of the easiest problem in LeetCode.