Given a positive integer n, you can apply one of the following operations:

  • If n is even, replace n with n / 2
  • If n is odd, replace n with either n + 1 or n - 1

Return the minimum number of operations needed for n to become 1.

Input & Output

Example 1 — Basic Case
$ Input: n = 8
Output: 3
💡 Note: 8 is even → 8/2 = 4, then 4/2 = 2, then 2/2 = 1. Total: 3 operations.
Example 2 — Odd Number Choice
$ Input: n = 7
Output: 4
💡 Note: 7 is odd → choose 7-1=6, then 6/2=3, then 3-1=2, then 2/2=1. Total: 4 operations.
Example 3 — Small Odd
$ Input: n = 3
Output: 2
💡 Note: 3 is odd → choose 3-1=2 (better than 3+1=4), then 2/2=1. Total: 2 operations.

Constraints

  • 1 ≤ n ≤ 231 - 1

Visualization

Tap to expand
Integer Replacement Problem INPUT n = 8 Binary: 1000 8 Rules: If n is even: n = n / 2 If n is odd: n = n + 1 or n = n - 1 GREEDY ALGORITHM 1 8 is even 8 / 2 = 4 2 4 is even 4 / 2 = 2 3 2 is even 2 / 2 = 1 4 Reached 1 Stop! Goal achieved 8 4 2 1 Path visualization: FINAL RESULT Operations needed: 3 OK - Solved! Operation Breakdown: Op 1: 8 / 2 = 4 Op 2: 4 / 2 = 2 Op 3: 2 / 2 = 1 Total: 3 operations Key Insight: For powers of 2 (like 8), the greedy approach is optimal: just keep dividing by 2. For odd numbers, prefer n-1 unless (n+1) creates more trailing zeros in binary, except when n=3, always use n-1. This minimizes total operations to reach 1. TutorialsPoint - Integer Replacement | Greedy Approach
Asked in
Google 25 Microsoft 18 Facebook 15 Amazon 12
28.4K Views
Medium Frequency
~15 min Avg. Time
856 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