Leetcode Day 1: Two Sum

The problem is as follow:

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]
Enter fullscreen mode
Exit fullscreen mode

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

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Enter fullscreen mode
Exit fullscreen mode

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]
Enter fullscreen mode
Exit fullscreen mode

Here is how I solved it:

  • We want to create a dictionary named index_map to store the integers in nums and their corresponding indices.
index_map = {}
Enter fullscreen mode
Exit fullscreen mode
  • Then, we will use enumerate to get both index i and value num of each element in nums.
    For each integer, let’s calculate the complement, which is the difference between the target and the current element num.
for i, num in enumerate(nums): n = target - num
Enter fullscreen mode
Exit fullscreen mode
  • Now check the dictionary: if n is in the dictionary, it means we have found the two integers that add up to the target Return the n index and the current index as a list.
if n in index_map: return [index_map[n], i]
Enter fullscreen mode
Exit fullscreen mode
  • Else, if n is not in the dictionary, add the current element num and index to the dictionary.
index_map[num] = i
Enter fullscreen mode
Exit fullscreen mode

Here is the completed solution:

class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: index_map = {} for i, num in enumerate(nums): n = target - num if n in index_map: return [index_map[n], i] index_map[num] = i
Enter fullscreen mode
Exit fullscreen mode

Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Lifestyle and personal development. Mobile app development.