Keep Multiplying Found Values by Two - Problem

You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums.

You then do the following steps:

  • If original is found in nums, multiply it by two (i.e., set original = 2 * original).
  • Otherwise, stop the process.
  • Repeat this process with the new number as long as you keep finding the number.

Return the final value of original.

Input & Output

Example 1 — Basic Case
$ Input: nums = [5,3,6,1,12], original = 3
Output: 24
💡 Note: 3 is found → double to 6. 6 is found → double to 12. 12 is found → double to 24. 24 is not found → return 24
Example 2 — Single Step
$ Input: nums = [2,7,9], original = 4
Output: 4
💡 Note: 4 is not found in the array, so return the original value 4
Example 3 — Multiple Doublings
$ Input: nums = [1,2,4,8], original = 1
Output: 16
💡 Note: 1 → 2 → 4 → 8 → 16. Since 16 is not in array, return 16

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i], original ≤ 1000

Visualization

Tap to expand
Keep Multiplying Found Values by Two INPUT nums array: 5 3 6 1 12 0 1 2 3 4 original = 3 3 Hash Set Created: {1, 3, 5, 6, 12} Input Parameters: nums = [5,3,6,1,12] ALGORITHM STEPS 1 Build Hash Set O(n) lookup enabled 2 Check: 3 in set? Yes! 3 * 2 = 6 3 Check: 6 in set? Yes! 6 * 2 = 12 4 Check: 12 in set? Yes! 12 * 2 = 24 5 Check: 24 in set? No! STOP Multiplication Chain: 3 --> 6 --> 12 --> 24 x2 x2 x2 STOP FINAL RESULT 24 not found in Hash Set Process terminates Final Value: 24 Verification: 3 in nums? Yes [OK] 6 in nums? Yes [OK] 12 in nums? Yes [OK] 24 NOT in nums Return 24 Key Insight: Using a Hash Set provides O(1) lookup time for each search operation, making the overall time complexity O(n) for building the set plus O(log(max/original)) for the multiplications. This is much faster than O(n) linear search for each check, especially with many doublings. TutorialsPoint - Keep Multiplying Found Values by Two | Hash Set Optimization Approach
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen