#2154

Keep Multiplying Found Values by Two

Easy
ArrayHash TableSortingSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a set for quick lookups allows us to efficiently check if 'original' exists in 'nums', reducing the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Convert 'nums' into a set for O(1) average time complexity for lookups.
  2. 2Step 2: Initialize a loop that continues while 'original' is in the set.
  3. 3Step 3: Multiply 'original' by 2 each time it is found.
  4. 4Step 4: Return the final value of 'original'.
solution.py5 lines
1def findFinalValue(nums, original):
2    num_set = set(nums)
3    while original in num_set:
4        original *= 2
5    return original

Complexity note: The time complexity is O(n) because we create a set from the array, which takes O(n) time, and each lookup for 'original' is O(1).

  • 1Using a set allows for faster lookups compared to an array.
  • 2The problem can be viewed as a simulation of multiplying values until a condition fails.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.