Leetcode 2154. Keep Multiplying Found Values by Two
You’re given an integer array nums. You are also given an integer original which is the starting value. Your task is to find if the value original exists in the nums array. If it does, multiply the original value by two and repeat the process until the value original is no longer present in nums. Return the final value of original.
Input: nums = [5,3,6,1,12], original = 3
Output: 24
Input: nums = [2,7,9], original = 4
Output: 4
1 <= nums.length <= 10001 <= nums[i], original <= 1000nums array or keep it intact?
nums array intact.nums array unique or can they be duplicated?
nums array to a set to allow O(1) time complexity checks for the presence of values.original value exists in the set.original by 2 and continue.original.#include <vector>
#include <unordered_set>
int findFinalValue(std::vector<int>& nums, int original) {
std::unordered_set<int> numSet(nums.begin(), nums.end());
while (numSet.find(original) != numSet.end()) {
original *= 2;
}
return original;
}
vector to set:
nums.original could double up to the maximum value possible within the integer range. However, practically, the loop will run for a limited number of iterations due to the constraints provided.Overall, the time complexity can be considered O(n) for most practical purposes, considering the conversion to set and membership checking form the bulk of the operations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?