Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the number of operations to reduce n to 1: if even halve it, else add or subtract 1 (choose optimally).

Problem: Find the number of operations to reduce n to 1: if even halve it, else add or subtract 1 (choose optimally).
def steps(n):
    c = 0
    while n != 1:
        if n % 2 == 0: n //= 2
        elif n == 3 or n % 4 == 1: n -= 1
        else: n += 1
        c += 1
    return c
print(steps(8), steps(7), steps(15), steps(3))
What is printed?
  1. A. 3 4 6 2
  2. B. 3 5 5 2
  3. C. 3 4 5 3
  4. D. 3 4 5 2

Correct answer: D. 3 4 5 2

For odd n, move to the neighbour divisible by 4 (more trailing zeros to halve away), except 3 → 2 → 1. 7 → 8 → 4 → 2 → 1 = 4; 15 → 16 → 8 → 4 → 2 → 1 = 5 (subtracting gives 14 → 7 → … = 6). O(log n).

More Coding Interview Problems questions

Exams that ask this topic