#397

Integer Replacement

Medium
Dynamic ProgrammingGreedyBit ManipulationMemoizationBit ManipulationGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(n)
O(1)
💡

Intuition

Time O(log n)Space O(1)

The optimal solution uses a greedy approach combined with bit manipulation. It reduces the number of operations by choosing the best operation for odd numbers based on their binary representation.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a counter for operations.
  2. 2Step 2: While n is greater than 1, check if n is even or odd.
  3. 3Step 3: If n is even, divide by 2. If odd, check the last two bits to decide whether to increment or decrement n, aiming to make it even.
solution.py12 lines
1def integerReplacement(n):
2    count = 0
3    while n > 1:
4        if n % 2 == 0:
5            n //= 2
6        else:
7            if n == 3 or (n & 2) == 0:
8                n -= 1
9            else:
10                n += 1
11        count += 1
12    return count

Complexity note: The time complexity is O(log n) because each operation effectively reduces n by half in the case of even numbers, and the number of operations is logarithmic relative to the size of n.

  • 1For odd numbers, the choice between incrementing or decrementing can significantly affect the number of operations needed.
  • 2Understanding binary representation helps in determining the optimal path for odd numbers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.