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?- A. 4 3 3
- B. 5 3 7
- C. 4 3 7
- 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
- Problem: Return the largest number ≤ n whose digits are non-decreasing from left to right. python def mono(n): d = list(str(n)); mark =…
- Problem: A string has '(', ')' and '', where '' may act as '(', ')' or nothing. Is it balanceable? Track the range [lo, hi] of possible…
- Problem: Bags hold balls; an operation splits one bag into two bags (any sizes). With at most ops operations, minimise the largest bag…
- Problem: Tower of Hanoi: move n disks from peg A to peg C using B, recording every move. python moves = [] def hanoi(n, a, b, c): if n ==…
- Problem: Mirror a binary tree (swap every node's children) and print its inorder traversal. Trees are built from a level-order list by…
- Problem: Generate all distinct subsets of a multiset of coupon values (skip equal values at the same recursion depth). python def…