Data Structures & AlgorithmsVery hardProduct company OA

Problem: A broken calculator shows start and supports only 'double' and 'decrement by 1'. Find the minimum operations to reach target. Work backwards: halve target when even, else add 1.

Problem: A broken calculator shows `start` and supports only 'double' and 'decrement by 1'. Find the minimum operations to reach `target`. Work backwards: halve target when even, else add 1.
def broken(start, target):
    ops = 0
    while target > start:
        target = target // 2 if target % 2 == 0 else target + 1
        ops += 1
    return ops + start - target
print(broken(4, 13), broken(6, 20), broken(9, 2))
What is printed?
  1. A. 4 3 3
  2. B. 5 3 7
  3. C. 4 3 7
  4. D. 4 4 7

Correct answer: C. 4 3 7

Reversed operations are 'halve' (only on even numbers) and 'add 1'; halving as soon as possible is optimal while target > start, and the rest is covered by decrements (start − target additions in reverse). 13 → 14 → 7 → 8 → 4: 4 ops (forward: 4 → 8 → 7 → 14 → 13). 20 → 10 → 5, then 6 − 5 = 1 → 3. If target < start only decrements help: 9 − 2 = 7. Forward greedy (double while below target) fails – e.g. 4 → 8 → 16 → … wastes steps. O(log target).

More Coding Interview Problems questions

Exams that ask this topic