Compute min operations to transform integers
Company: Akuna Capital
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Take-home Project
Quick Answer: This question evaluates algorithmic problem-solving skills related to integer transformations and reasoning about sequences of allowed operations, focusing on optimizing the number of steps. It is commonly used in the Coding & Algorithms domain to assess practical application of algorithmic thinking and time-complexity analysis, testing efficiency reasoning rather than purely conceptual knowledge.
Constraints
- A and B are integers.
- When B <= A, the answer is simply A - B (only subtractions are useful).
- When B > A, multiplications are required and the reverse-greedy halving applies.
- Values can be large (e.g. up to ~10^9); the O(log B) approach handles them instantly.
Examples
Input: (1, 2)
Expected Output: 1
Explanation: 1 x 2 = 2 in a single multiply operation.
Input: (9, 1)
Expected Output: 8
Explanation: B < A, so subtract 1 eight times: 9 -> 8 -> ... -> 1.
Input: (2, 10)
Expected Output: 5
Explanation: 2 x2=4, 4-1=3, 3 x2=6, 6-1=5, 5 x2=10. Five operations.
Input: (100, 500)
Expected Output: 41
Explanation: Reverse-greedy from 500: 500/2=250, 250/2=125, 125+1=126, 126/2=63 (4 ops), then 100-63=37 subtractions -> 4 + 37 = 41.
Input: (5, 5)
Expected Output: 0
Explanation: A already equals B, so no operations are needed.
Input: (3, 1)
Expected Output: 2
Explanation: B < A: subtract 1 twice, 3 -> 2 -> 1.
Input: (1, 1000000)
Expected Output: 28
Explanation: Reverse-greedy repeatedly halves 1000000 (incrementing when odd) down to 1 in 28 operations.
Input: (7, 22)
Expected Output: 4
Explanation: Reverse from 22: 22/2=11, 11+1=12, 12/2=6 (3 ops); then 7-6=1 subtraction -> 4 total. Forward: 7-1=6, 6 x2=12, 12-1=11, 11 x2=22.
Input: (10, 3)
Expected Output: 7
Explanation: B < A, so subtract 1 seven times: 10 -> 3.
Input: (2, 1)
Expected Output: 1
Explanation: Edge boundary: B = A - 1, a single subtraction.
Hints
- Working forward from A is hard because multiply-by-2 branches explode. Try reasoning backward from B instead.
- Invert the operations: 'multiply by 2' becomes 'divide by 2' (only when the value is even); 'subtract 1' becomes 'add 1'.
- While B > A: if B is even, halve it; if B is odd, add 1 to make it even. Count each as one operation.
- Once B <= A, the remaining cost is exactly A - B subtractions — no multiplications can help anymore.