Integer Replacement (LeetCode 397): Solution and Explanation

Medium
Dynamic Programming
Greedy
Bit Manipulation
Memoization

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

  1. Seed memo[1] = 0.
  2. steps(x): if x is in the memo, return it.
  3. If x is even, best = 1 + steps(x / 2). Otherwise best = 1 + min(steps(x + 1), steps(x - 1)).
  4. 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
  1. steps(7): 7 is odd, so try 8 and 6.
  2. steps(8) = 1 + steps(4) = 1 + 1 + steps(2) = 1 + 1 + 1 + steps(1) = 3.
  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.
  4. 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)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(log n)

Each bit length contributes at most two distinct values, and each is computed once.

Space

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.