Find two numbers that add up to a target.

Given an array, find indices of two numbers in the array that add up to a target integer. For example, given an array array = [2,7,11,15] , and a target value of 9 , the expected output is [0,1] . This is because array[0]+array[1] = 9 .


Solution 1

Following is the naiive solution with a very straightforward solution.

def twoSum(self, nums: List[int], target: int) -> List[int]: f_idx = 0 s_idx = 0 for f_idx,val in enumerate(nums): for s_idx in range(f_idx+1,len(nums)): if val+nums[s_idx] == target: return [f_idx,s_idx] # should not return here return [-1,-1]