You are playing a game that starts with a score of 1. Your goal is to reach a target score. In each move, you can:
Increment your current score by 1.
Double your current score.
However, you have a limit on how many times you can use the "double" operation (maxDoubles). You want to reach the target in the minimum number of moves.
2. Why is this asked in interviews?
Companies like Meta and Amazon ask this to test Greedy logic and Backward Thinking.
Interviewer's look for:
Optimization Strategy: Does the candidate realize that doubling is more effective when the number is larger?
Backward Approach: Understanding that starting from target and going down to 1 is much easier than going from 1 to target.
Efficiency: Solving the problem in O(log(target)) time.
3. Algorithmic pattern used
The pattern is Greedy (Backward).
Instead of going from 1 to target, go from target to 1:
If the current number is even and you still have doubles left, divide it by 2. This is equivalent to doubling in the forward direction.
If the current number is odd, subtract 1.
If you run out of doubles, you must use the decrement operation for all remaining steps. The number of steps will be current_number - 1.
4. Example explanation
target = 19, maxDoubles = 2
19 is odd → 18 (1 move)
18 is even, have doubles → 9 (1 move, 1 double left)
9 is odd → 8 (1 move)
8 is even, have doubles → 4 (1 move, 0 doubles left)
Out of doubles! Moves needed = 4−1=3.
Total moves = 1+1+1+1+3=7.
Forward verification: 1→2→4→8→9→18→19. (Wait, 1→2→4→8 is 3 moves, then 8→9, then 9→18, then 18→19. Total 6?)
Let's re-calculate:
Backward: 19−118/29−18/24−13−12−11.
Moves: 1 (for 18), 1 (for 9), 1 (for 8), 1 (for 4), 3 (to get to 1). Total 7.
5. Common mistakes candidates make
Forward Greedy: Trying to use doubles as soon as possible. Doubling 1→2 only saves 1 move. Doubling 50→100 saves 50 moves. You should always save your doubles for the largest possible numbers.
Recursive solutions: A simple loop is more efficient and avoids potential stack overflow for very large targets (109).
Not handling maxDoubles = 0: In this case, the answer is simply target - 1.
6. Interview preparation tip
Whenever a problem involves "doubling" or "halving" with a limit, try working backwards. It often makes the greedy choice obvious (e.g., "only divide if it's even").