The Two Sum question is a leetcode question that works on finding two numbers in an array whose sum equals a given target
Let’s understand the question:
Given an array nums and a target value, return the indices of the two numbers such that they add up to the target.
example
target = 9
Output : [2,7]
because 2+ 7 -> 9
*Approach *
I came to know there are 3 ways to solve this question
they were
*brute force - > comparing all possible pairs
hashing -> store all previous traverse
optimized -> by difference *
I choose optimized approach it is the most time and memory efficent approach, I started with a question "Do I really need to check all pairs?”
That felt slow and so was hashing “Can I remember what I’ve already seen?”
step 1: Target - current number
and move that value to another list
dif = []
loop 1
nums = [2, 7, 11, 15]
dif = []
9 - nums[0] - > 2
2 not in dif
so -> dif = [2]
loop 2
nums = [2, 7, 11, 15]
9-nums[1] -> 2
2 in dif
then that means the pair is found
Algorithm
def twoSum(self, nums, target):
seen = {} # number : index
for i in range(len(nums)):
complement = target - nums[i]
if complement in seen:
return [seen[complement], i]
seen[nums[i]] = i
Top comments (0)