Here is a quick exercise: given a target number K and a set of numbers, find, if any, a pair of numbers that sum up to K.
We can do this in O(N) time and space by walking on the input set of numbers and recording somewhere all the complements we would need to find to sum up to K.
Example: target is 10 and input is 1, 5, 7, 3.
If we could sum up to 10 using 1, we'd need to have a 9 available. If we encounter a 9 while walking the array, we know we have the pair (1,9) and have one possible solution.
You can check my implementation of numbersAddUpToK on my Gist along with some tests in NumbersAddUpToKJTests. I make use of a Pair object as well.
No comments:
Post a Comment
With great power comes great responsibility