Leetcode #1 — Two Sum (Python)

Dhairya Dave
3 min readDec 10, 2020

Hello everyone, my name is Dhairya Dave and this is my first post on Medium! I will be uploading solutions to Leetcode questions using the Python programming language. I will try to keep each post as concise as possible, while trying my best to deliver content that’s useful for the readers. With that being said, let’s get started!

Today, we’ll be looking at the Two Sum problem. This problem is categorized as “Easy” on Leetcode.

Problem Statement

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.

Examples from Leetcode

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

Output explained:

The list containing the indices [0,1] should be returned as nums[0] + nums[1] = 2 + 7 = 9 (target)

Input: nums = [3,2,4], target = 6
Output: [1,2]
Input: nums = [3,3], target = 6
Output: [0,1]

Solution

Explanation (with two examples):

1. Let's call: twoSum([2, 7, 11, 15], 26) - Start by creating a dictionary ‘d’. - The 'idx' and 'num' values in "for idx, num in enumerate(nums)", where nums = [2,7,11,15] look something like this: idx -> num
0 -> 2
1 -> 7
2 -> 11
3 -> 15
- Iteration 1: idx = 0,
num = 2,
difference = target - num = 26 - 2 = 24
if 24 in d -> FalseSo, we set d[2] = 0 ... d is now {2: 0}- Iteration 2:idx = 1,
num = 7,
difference = target - num = 26 - 7 = 19
if 19 in d -> FalseSo, we set d[7] = 1 ... d is now {2: 0, 7: 1}- Iteration 3:idx = 2,
num = 11,
difference = target - num = 26 - 11 = 15
if 15 in d -> FalseSo, we set d[11] = 2 ... d is now {2: 0, 7: 1, 11: 2}- Iteration 4:idx = 3,
num = 15,
difference = target - num = 26 - 15 = 11
if 11 in d -> True ... return [d[difference], idx] = [d[11], 3] = [2,3]
2. Let's call: twoSum([3, 6, 9, 12], 15)- Iteration 1:idx = 0,
num = 3,
difference = target - num = 15 - 3 = 12
if 12 in d -> FalseSo, we set d[3] = 0 ... d is now {3: 0}- Iteration 2:idx = 1,
num = 6,
difference = target - num = 15 - 6 = 9
if 9 in d -> FalseSo, we set d[6] = 1 ... d is now {3: 0, 6: 1}- Iteration 3:idx = 2,
num = 9,
difference = target - num = 15 - 9 = 6
if 6 in d -> True ... return [d[difference], idx] = [d[6], 2] =
[1, 2]

That’s all, folks! Happy Learning!

Dhairya Dave

--

--

Dhairya Dave
Dhairya Dave

No responses yet