Leetcode 2154. Keep Multiplying Found Values by Two
You are given an integer array nums. You are also given an integer original which is guaranteed to be one of the elements in nums.
You should do the following operation as long as you can:
original is in nums, multiply it by two (i.e., set original = 2 * original).Return the final value of original.
Example 1:
Input: nums = [5, 3, 6, 1, 12], original = 3
Output: 24
Example 2:
Input: nums = [2, 7, 9], original = 4
Output: 4
Q: What is the size limit of the input array nums?
A: There is no explicit size limit given, but we may assume typical constraints like up to 10^4 elements.
Q: Is nums always a non-empty array?
A: Yes, it’s stated in the problem description.
Q: Are there any constraints on the values within nums?
A: The problem doesn’t specify, but typically array elements can range from -10^4 to 10^4.
Q: Can original be a negative number?
A: Technically yes, but it’s mentioned that original is guaranteed to be one of the elements in nums.
We’ll use a HashSet to store the elements of nums for O(1) average-time complexity checks to see if original is in nums.
We iterate while original is found in the set. Every time it’s found, we multiply original by 2.
We continue this process until original no longer exists in nums.
Finally, we return the value of original.
import java.util.HashSet;
public class Solution {
public int findFinalValue(int[] nums, int original) {
// Step 1: Create a HashSet from the elements of nums
HashSet<Integer> numSet = new HashSet<>();
for (int num : nums) {
numSet.add(num);
}
// Step 2: Multiply 'original' by 2 until it's no longer in the set
while (numSet.contains(original)) {
original *= 2;
}
// Step 3: Return the final value of 'original'
return original;
}
}
nums (each insertion is O(1) amortized time).Checking in HashSet: In the worst case, we might check log(N) times (each check O(1)).
Suppose original starts with the minimum element and needs to be doubled until a maximum possible value within the range of given constraints (like say 32,768).
Max multiplications needed will be bounded by the number of bits, usually less than or equal to 14 (log2 (10^4)).
HashSet.This method ensures both time and space efficiency while solving the problem effectively.
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?