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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay