1. Two Sum

Easy 35,049 1,109 Accepted: 7,226,574 Submitted: 14,788,825 Acceptance Rate: 48.87%

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

Analysis

1. What is the min and max size of nums?
2. What is the range of int values? Can they be negative?
3. Do we need to worry about integer overflow (not a real issue in Python)?
4. What happens if there are no solution?
5. Can we use the same index twice? What about the same number but in different indexes?
6. What happens if there are multiple valid answers?

Design

1. What do we optimize for, speed or space?
2. The brute force solution would be to look through the entire array for other numbers that add up to the target for each index. This would be O(n^2).
3. Can we do better? If the array is sorted, would that help? We can use a double pointer approach at both ends of the array to attempt to find the target. This would be O(nlogn) due to sorting.
4. How about we sacrifice space for speed? For the solution in step 2, we have to iterate through the list a second time because we do not keep track of previously seen numbers. If we use a dictionary to keep track of seen numbers, we can get a linear solution.

Code

num_to_idx = {}

for idx, num in enumerate(nums):
desired_num = target - num
if desired_num in num_to_idx:
return [num_to_idx[desired_num],idx]

num_to_idx[num] = idx
raise ValueError("No solution")

Test

1. Normal scenario (different numbers that match target)
2. A single index used twice will map to the target (check that our solution doesn't do this)
3. Same numbers but in different indexes that will match to target
4. (Not applicable) but a non-matching scenario
5. (Not applicable) but a overflow scenario

Complexity Analysis

n = nums
There is one for loop iterating against each element in nums so time time complexity is O(n).
We have a dictionary num_to_idx that can potentially store almost all elements in nums so space is O(n).

Post-Solving Commentary

1. My chosen solution was the optimal one-pass hash table but I didn't consider the two-pass hash table mentioned in the solutions.
2. This is a great explanation on this and other sums problems.