leetcode

Keep Multiplying Found Values by Two - Link

Question Description

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:


Constraints


Approach

Use 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).


Dry Run

Example Input: nums = [5,3,6,1,12], original = 3

Step-by-step execution:

Final Answer = 24


Solution

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;
    }
}

Time and Space Complexity

Back to All Problems