Keep Multiplying Found Values by Two

easy math hash set

Problem

You are given an array of integers nums and a starting integer original. Repeatedly check whether original appears in nums: if it does, replace original with original × 2 and check again; if it does not, stop. Return the final value of original once it can no longer be found in nums.

Inputnums = [5, 3, 6, 1, 12], original = 3
Output24
3 is present → 6; 6 is present → 12; 12 is present → 24; 24 is not present, so the answer is 24.

def find_final_value(nums, original):
    seen = set(nums)
    while original in seen:
        original *= 2
    return original
function findFinalValue(nums, original) {
  const seen = new Set(nums);
  while (seen.has(original)) {
    original *= 2;
  }
  return original;
}
class Solution {
    public int findFinalValue(int[] nums, int original) {
        Set<Integer> seen = new HashSet<>();
        for (int x : nums) seen.add(x);
        while (seen.contains(original)) {
            original *= 2;
        }
        return original;
    }
}
int findFinalValue(vector<int>& nums, int original) {
    unordered_set<int> seen(nums.begin(), nums.end());
    while (seen.count(original)) {
        original *= 2;
    }
    return original;
}
Time: O(n) Space: O(n)