Solve power jumps and graph tour
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This pair of problems evaluates algorithmic problem-solving in number representation and combinatorial graph optimization, focusing on competencies in bitwise/number reasoning for minimal operations and graph traversal/route optimization for a Hamiltonian tour.
Part 1: Minimum Operations Using Signed Powers of Two
Constraints
- -10^18 <= n <= 10^18
- Each operation may add or subtract exactly one power of two
- The answer should be computed efficiently in O(log |n|) time
Examples
Input: 0
Expected Output: 0
Explanation: It is already 0, so no operations are needed.
Input: 7
Expected Output: 2
Explanation: One optimal sequence is 7 + 1 = 8, then 8 - 8 = 0.
Input: 10
Expected Output: 2
Explanation: 10 - 2 = 8, then 8 - 8 = 0.
Input: 15
Expected Output: 2
Explanation: 15 + 1 = 16, then 16 - 16 = 0.
Input: -13
Expected Output: 3
Explanation: For example: -13 + 16 = 3, then 3 - 4 = -1, then -1 + 1 = 0.
Hints
- Think in binary. If n is even, the lowest bit is already 0, so divide the problem by 2 conceptually.
- When n is odd, decide whether adding 1 or subtracting 1 leads to a better future. Checking n % 4 is enough in most cases.