Integer Replacement (LeetCode 397): Solution and Explanation
Halve n when it is even, step it up or down by one when it is odd, and return the fewest moves that bring it to 1.
Intuition
Write steps(x) for the fewest moves from x to 1. An even x has only one move, so steps(x) = 1 + steps(x / 2). An odd x has two, so steps(x) = 1 + min(steps(x + 1), steps(x - 1)).
Both odd branches are even, so they halve on the next move. The two branches quickly meet again: halving x + 1 and x - 1 gives neighbouring numbers, and their subproblems overlap.
With a memo, each value is solved once. At every bit length only two neighbouring values ever appear, so the memo stays tiny even for n near 2^31.
Approach: Memoized recursion
- Seed memo[1] = 0.
- steps(x): if x is in the memo, return it.
- If x is even, best = 1 + steps(x / 2). Otherwise best = 1 + min(steps(x + 1), steps(x - 1)).
- Store memo[x] = best and return it. The answer is steps(n). Use 64-bit integers so x + 1 cannot overflow at n = 2^31 - 1.
Step-by-step example
n = 7
- steps(7): 7 is odd, so try 8 and 6.
- steps(8) = 1 + steps(4) = 1 + 1 + steps(2) = 1 + 1 + 1 + steps(1) = 3.
- steps(6) = 1 + steps(3). steps(3) is odd: steps(4) = 2 is in the memo, steps(2) = 1 is in the memo, so steps(3) = 1 + min(2, 1) = 2 and steps(6) = 3.
- steps(7) = 1 + min(3, 3) = 4. Output: 4.
Code: Python, Java, C++
1class Solution:
2 def integerReplacement(self, n: int) -> int:
3 memo = {1: 0}
4 def steps(x):
5 if x in memo:
6 return memo[x]
7 if x % 2 == 0:
8 memo[x] = 1 + steps(x // 2)
9 else:
10 memo[x] = 1 + min(steps(x + 1), steps(x - 1))
11 return memo[x]
12 return steps(n)1class Solution {
2 private Map<Long, Integer> memo = new HashMap<>();
3
4 public int integerReplacement(int n) {
5 memo.put(1L, 0);
6 return steps((long) n);
7 }
8
9 private int steps(long x) {
10 if (memo.containsKey(x)) {
11 return memo.get(x);
12 }
13 int best;
14 if (x % 2 == 0) {
15 best = 1 + steps(x / 2);
16 } else {
17 best = 1 + Math.min(steps(x + 1), steps(x - 1));
18 }
19 memo.put(x, best);
20 return best;
21 }
22}1class Solution {
2 unordered_map<long long, int> memo;
3
4 int steps(long long x) {
5 if (memo.count(x)) {
6 return memo[x];
7 }
8 int best;
9 if (x % 2 == 0) {
10 best = 1 + steps(x / 2);
11 } else {
12 best = 1 + min(steps(x + 1), steps(x - 1));
13 }
14 memo[x] = best;
15 return best;
16 }
17
18public:
19 int integerReplacement(int n) {
20 memo[1] = 0;
21 return steps(n);
22 }
23};Time and space complexity
O(log n)
Each bit length contributes at most two distinct values, and each is computed once.
O(log n)
The memo and the recursion depth both grow with the number of bits.
Other approaches
Greedy on the low bits (time O(log n), space O(1))
For an odd x, go down if x == 3 or x % 4 == 1, otherwise go up. Going up when x ends in 11 turns a run of 1 bits into 0s, which halves faster. This uses O(1) space.
BFS from n (time O(n) worst case in practice, space O(n))
Breadth-first search over values reached from n finds the shortest path to 1. Correct, but it explores many more values than the memoized recursion.
Common mistakes
- Computing x + 1 in 32-bit int when n = 2147483647, which overflows to a negative number.
- Always going down for odd x. 15 -> 16 -> 8 -> 4 -> 2 -> 1 takes 5 moves, while 15 -> 14 -> 7 -> ... takes 6.
- Building a bottom-up array of size n. With n up to 2^31 - 1 that is far too much memory; only the reachable values matter.
- Forgetting the special case 3 in the greedy version: 3 -> 2 -> 1 beats 3 -> 4 -> 2 -> 1.
Frequently asked questions
Why is this a dynamic programming problem if a greedy rule exists?
The recurrence over x / 2, x + 1 and x - 1 is the direct definition of the answer, and memoizing it is the standard DP view. The greedy rule is a shortcut that you can prove from the same recurrence.
How many states does the memo hold?
At most about two per bit length, so under 100 for any 32-bit n. For n = 2^31 - 1 the recursion stores about 90 values.
Could the recursion go deeper than the bit length?
Each pair of moves at least halves the value, so the depth is about twice the number of bits, roughly 64 at most. That is safe for recursion in every language.