Inputs
Problem 1: Two Sum
Description
Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.
- Each input is guaranteed to have exactly one solution.
- You may not use the same element twice.
- The answer can be returned in any order.
Examples
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 <= 10^4-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9- Only one valid answer exists.
Follow Up
Can you come up with an algorithm that is less than (O(n^2)) time complexity?
Steps
- As you iterate over the array, keep adding elements to a list.
- While considering a particular element, calculate the difference from target that is required.
- If this difference is in the list, we have found a pair
Implementation
target_hashmap = {}
for i, num in enumerate(nums):
difference = target - num
if difference in target_hashmap:
print("found")
else:
target_hashmap[num] = i
found
Submitted Code
from typing import List
def twoSum(nums: List[int], target: int) -> List[int]:
target_hashmap = {}
for i, num in enumerate(nums):
difference = target - num
if difference in target_hashmap:
# print("found")
return (i, target_hashmap[difference])
else:
target_hashmap[num] = i
nums = [2,7,11,15]
target = 9
twoSum(nums, target)
(1, 0)
Leave a Reply