1. Two Sum — LeetCode(Python)

Palash Sharma
2 min readJul 2, 2022

I got you!

Problem:

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]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

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

Example 3:

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

Constraints:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

Solution:

num_dict = {}
for i, num in enumerate(nums):
n = target - num
if n not in num_dict:
num_dict[num] = i
else:
return [num_dict[n], i]

Explanation —

We create a dictionary where we store the numbers that we encounter while traversing the array nums.

We create a key value pair between the number and it’s index, which we will use later.

If we come across such a number, that when added with a previously encountered number, sums up to the target value, we return the indices of both these numbers.

We don’t have to think of the case where we return False, because we are given that exactly one solution always exists.

Time and Space Complexity —

Creating a hash table takes linear space and traversing through the given array requires linear time.

Thus, if n is the number of elements in the array nums,

Time Complexity: O(n)

Space Complexity: O(n)

Feel free to ask any related questions in the comment section or the links provided down below.

I don’t have friends:

Let’s be friends!

Connect with me on:

LinkedIn

GitHub

Instagram (I know. Very professional)

Jai Shri Ram 🙏

--

--