You are given an array of integers nums. Your task is to find a value, original, which is in the nums array and keep multiplying it by 2 as long as it is present in the array. Once the value does not exist in the array, return the final value.
nums:
nums array?nums?original value always be chosen from the nums array?original must be a value from the nums array.original.nums into a set to allow O(1) average-time complexity for checking the presence of values.original is in the set, multiply it by 2.original is not found in the set, break the loop and return the current value of original.This ensures that the solution is efficient and leverages fast membership testing.
nums to a set: O(n)original starts very small and doubles many times before it is not found, the loop can run multiple times, but still, this would be much fewer operations compared to any linear or quadratic approach.Hence, the overall time complexity would be approximately O(n).
Here’s how you can implement this in Python:
def findFinalValue(nums, original):
nums_set = set(nums)
while original in nums_set:
original *= 2
return original
nums = [5, 3, 6, 1, 12] and original = 3:
original = 3 is in nums_set -> multiply original by 2 -> original = 6.original = 6 is in nums_set -> multiply original by 2 -> original = 12.original = 12 is in nums_set -> multiply original by 2 -> original = 24.original = 24 is not in nums_set, return original = 24.This approach ensures we find the correct value efficiently.
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?