Magicsheet logo

Integer Replacement

Medium
97.8%
Updated 6/1/2025

Integer Replacement

1. What is this problem about?

The Integer Replacement interview question gives you a positive integer nn. You can perform two operations:

  1. If nn is even, replace nn with n/2n/2.
  2. If nn is odd, replace nn with either n+1n+1 or n1n-1. You need to find the minimum number of replacements needed to reach 1.

2. Why is this asked in interviews?

Companies like Uber and Google ask the Integer Replacement coding problem to test a candidate's ability to optimize a decision tree. While it looks like a simple BFS or DP problem, there is a greedy bitwise strategy that solves it in O(logN)O(\log N). It evaluations your skills in Bit Manipulation interview patterns and Memoization.

3. Algorithmic pattern used

This problem follows the Greedy Bit Manipulation pattern.

  • If nn is even, you must divide by 2.
  • If nn is odd, you want to choose the operation that creates more trailing zeros in binary (making it easier to divide by 2 later).
  • Rule: If n=3n = 3, use n1n-1. For all other odd numbers, if n % 4 == 3, use n+1n+1; otherwise, use n1n-1.

4. Example explanation

n=7n = 7 (Binary 111)

  1. 77 is odd, 7 % 4 == 3. Use n+1n+1. n=8n=8 (Binary 1000). Count=1.
  2. 84218 \to 4 \to 2 \to 1. Count = 1+3=41 + 3 = 4. If we used n1n-1: 763217 \to 6 \to 3 \to 2 \to 1. Count = 4. n=15n = 15 (Binary 1111)
  3. 1516842115 \to 16 \to 8 \to 4 \to 2 \to 1. Count = 5.
  4. 1514715 \to 14 \to 7 \dots would take longer.

5. Common mistakes candidates make

  • Integer Overflow: n+1n+1 can exceed the maximum 32-bit integer if nn is Integer.MAX_VALUE. Use a 64-bit long for the calculation.
  • Recursive TLE: Using recursion without memoization.
  • Greedy logic errors: Failing to recognize the special case for n=3n=3.

6. Interview preparation tip

Bitwise patterns (like checking n % 4) are very common in "minimum operations" problems. If a problem involves dividing by 2, always look at the binary representation to find the optimal path.

Similar Questions