You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums.
You then do the following steps:
1 <= nums.length <= 10001 <= nums[i], original <= 1000Use a HashSet to store all numbers from nums for O(1) lookups. Then repeatedly check if the current original value exists in the set. If it does, multiply by 2 and continue. If not, break the loop and return the current original value.
This approach works because:
Alternative approaches like linear search through the array for each iteration would work but would be less efficient (O(n²) in worst case vs O(n) with HashSet).
Example Input: nums = [5,3,6,1,12], original = 3
Step-by-step execution:
Final Answer = 24
class Solution {
public int findFinalValue(int[] nums, int original) {
Set<Integer> set = new HashSet<>();
for(int i = 0; i < nums.length; i++){
set.add(nums[i]);
}
while(true){
if(set.contains(original)){
original *= 2;
}else{
break;
}
}
return original;
}
}