Minimize steps to reduce integer
Company: Salesforce
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithm design skills and proficiency with integer operations and decision-making under parity constraints, testing competencies such as bitwise reasoning, greedy and dynamic-programming intuition, and complexity analysis.
Constraints
- 1 <= n <= 2^61 - 1
- Each operation must be one of: divide by 2 when even, add 1 when odd, or subtract 1 when odd
Examples
Input: (1,)
Expected Output: 0
Explanation: n is already 1, so no steps are needed.
Input: (2,)
Expected Output: 1
Explanation: 2 is even, so divide by 2: 2 -> 1.
Input: (3,)
Expected Output: 2
Explanation: The best path is 3 -> 2 -> 1. Incrementing first would take 3 steps: 3 -> 4 -> 2 -> 1.
Input: (8,)
Expected Output: 3
Explanation: Repeatedly divide by 2: 8 -> 4 -> 2 -> 1.
Input: (7,)
Expected Output: 4
Explanation: One optimal path is 7 -> 8 -> 4 -> 2 -> 1, which takes 4 steps.
Input: (15,)
Expected Output: 5
Explanation: The best path is 15 -> 16 -> 8 -> 4 -> 2 -> 1, which takes 5 steps.
Input: (2305843009213693951,)
Expected Output: 62
Explanation: This is 2^61 - 1. Increment once to get 2^61, then divide by 2 exactly 61 times.
Hints
- For an odd number, compare what happens after choosing n - 1 versus n + 1. Which one creates more trailing zero bits in binary?
- There is one important exception to the n % 4 rule: handle n = 3 separately.