DEV Community

Simona Cancian
Simona Cancian

Posted on • Edited on

1

Leetcode Day 1: Two Sum Explained

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

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more