I am trying to solve a coding problem where I need to repeatedly double a number (original) as long as it exists in an integer array. To make the lookup faster, I am inserting all elements of the array into a HashSet. My understanding is that this should allow constant-time contains() checks.
However, when I put the doubling condition inside the loop that builds the set, my code fails on certain inputs. Here is the code:
public int findFinalValue(int[] nums, int original) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
if (set.contains(original)) {
original *= 2;
}
}
return original;
}
For example, with nums = [5,3,6,1,12] and original = 3, this code returns 12, but the correct result should be 24 because 3 → 6 → 12 → 24 (all appear in the array).
When I move the condition outside the loop like this:
while (set.contains(original)) {
original *= 2;
}
…it works correctly.
My question is:
Why does checking contains(original) inside the same loop where the set is being built cause incorrect behavior?
I assumed adding elements one by one and checking in the same pass should logically work, since ultimately the same set gets built.
Is there some detail about iteration order, timing of updates, or HashSet behavior that I am misunderstanding?
Any explanation about why the logic only works after the full set is constructed would be greatly appreciated.
[5,3,6,1,12].[12,5,3,6,1]when original is 3? I think you have to build the entire set first.originalis in the set and double it as long as it is. Would seem simpler to argue about to me.