I came across an interview question for which I am not sure what the correct answer is.
The problem is below.
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
The way I solved it by looping through the element and storing the diff between target and element as key and index of the current element in a map.
Then later on when the diff appears in the array, I can look up in map which element has this diff and at what index in the map.
Up to now it is fine.
However, for a follow-up question, "What if the elements are double"
I am not sure what is the issue if any.
When searching I came across a couple of posts mentioning correct way to compute a hashcode using logical shift and using or. However, I see the similar logic is used in Java's Double.hashcode function.
I thought that the problem could be when computing diff, there might be precision loss. Hence, it might end up mapping to a different hash bucket.
However, when I tried, I couldn't come up with such an input. What is the actual problem? And how do I test/solve it?
Java
I tried simply changing the numbers to double, but the logic worked fine.