Integer Replacement - Problem
Given a positive integer n, you need to find the minimum number of operations to transform it into 1 using the following rules:
- If
nis even: replacenwithn / 2 - If
nis odd: replacenwith eithern + 1orn - 1
The challenge lies in making the optimal choice when n is odd. Should you add 1 or subtract 1? The goal is to reach 1 in the fewest steps possible.
Example: For n = 8: 8 → 4 → 2 → 1 (3 operations)
For n = 7: 7 → 6 → 3 → 2 → 1 (4 operations) vs 7 → 8 → 4 → 2 → 1 (4 operations)
Input & Output
example_1.py — Python
$
Input:
n = 8
›
Output:
3
💡 Note:
8 → 4 → 2 → 1. Since 8 is even, we divide by 2 repeatedly until we reach 1. Total steps: 3.
example_2.py — Python
$
Input:
n = 7
›
Output:
4
💡 Note:
7 → 6 → 3 → 2 → 1 (4 steps) or 7 → 8 → 4 → 2 → 1 (4 steps). Both paths take 4 operations, but the first is found by our optimal strategy.
example_3.py — Python
$
Input:
n = 4
›
Output:
2
💡 Note:
4 → 2 → 1. Since 4 is even, we can divide by 2 twice. Total steps: 2.
Constraints
- 1 ≤ n ≤ 231 - 1
- n is a positive integer
- The answer is guaranteed to fit in a 32-bit integer
Visualization
Tap to expand
Understanding the Visualization
1
Start at height n
Begin your descent from the initial number
2
Even heights: Take elevator
When n is even, divide by 2 (fastest descent)
3
Odd heights: Choose wisely
When n is odd, pick +1 or -1 to set up better elevator opportunities
4
Bit pattern strategy
Use binary patterns: '11' ending → +1, '01' ending → -1
5
Reach base camp
Continue until you reach height 1
Key Takeaway
🎯 Key Insight: The optimal strategy treats this as a bit manipulation problem where we aim to create the maximum number of trailing zeros, allowing for more efficient consecutive divisions by 2.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code