#1 Programmer challenge
Given an array of integer and a given number. Find all pairs in the array that the summation of the pair numbers equal to the given number. Is it able to find a solution in O(1)?!
Given an array of integer and a given number. Find all pairs in the array that the summation of the pair numbers equal to the given number. Is it able to find a solution in O(1)?!
My thought:
As you iterate through the array, store the difference between the given number and array element in memory. If an element you come across in the array is in the set already, you've found a pair. Might be easier to see in code:
(In java since that's what I primarily use)
Note: I had to use a HashMap and not a HashSet because HashSet doesn't account for several of the same number in the array (eg. 5 which you see in my case above).
Edit: I think I solved the wrong problem, since you specified all pairs and not the count of pairs. Dunno where that came from. Easy enough to fix though, you just store both numbers as you find them and output that instead.
Hi, I am the new curator for @math-trail, a community dedicated to promoting the best articles on mathematics in its widest sense, including educational and cultural aspects.
I just upvoted your post - hope to see more in the future.
If you like to write about mathematics, then please follow @math-trail and I will follow you back and look forward to see fresh new content.
If you enjoy reading about mathematics, then please follow me so that you will receive the best content in your personal feed.
I am not a bot! Thanks!