Two Sum
Easy
Subject: Arrays & Hashing
Time Complexity
O(N)
Space Complexity
O(N)
Problem Description
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.
Optimal Solution
Pythondef twoSum(nums, target):
# Store value mapping to its index
seen = {}
for i, num in enumerate(nums):
diff = target - num
if diff in seen:
return [seen[diff], i]
seen[num] = i
return []