1. Two Sum
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.
Solution
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
found = {}
for idx, val in enumerate(nums):
if target-val in found:
return (idx, found[target-val])
else:
found[val] = idx
Time Complexity: O(n)
Space Complexity: O(n)
Explanation
x + y = z
The key to this problem is realizing that if the target is z and we're currently checking if y is a piece of our answer, then x would have to be z-y. Now that we know what we're looking for we can simply check if we've previously seen it (this can be made efficient with the use of a dictionary).