Hash Table
Problems
Two Sum
Given an array of integers & a target, compute all possible unique two sums that add to the target without replacement returning them as a list of lists. (variant of simpler unique soln problem)
Explore
t=4
1 2 3 4 5 6 0 -1
3 2 1 0-1-2 4 5
- Keep track of the value needed to add to reach target in a dictionary that maps value→index for return purposes.
- As a solution is found, add it to the solutions list.
Python Solution
Complexity
We iterate over the input once doing amortized constant time insertions & lookups in the hashmaps yielding O(n) time & space.
3Sum
Given an integer array, return all unique triplets that sum to zero|target without replacement.
Explore
t=0 t=0 -1 0 1 2 -1 4 -1 -1 0 1 2 4 -1 -1 2 -1 0 1 -1 0 1 → x
- Sort the array.
- Consider each array element as -t in a two sum hash table solution containing only the elements to the right of it.
- Use a set to check potential solutions for uniqueness. (sorted tuples are hashable)
Python Solution
Complexity
We sort the input in nlogn time & perform two nested iterations on the input array for an O(n^2) time & O(n) space.