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?- A. 3 4 6 2
- B. 3 5 5 2
- C. 3 4 5 3
- 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
- Problem: Find the minimum number of jumps for a knight to reach a target on an infinite board (BFS). python from collections import deque…
- Problem: Count the inversions of an array with merge sort. python def inv(a): if len(a) < 2: return a, 0 m = len(a) // 2 L, x =…
- Problem: Return the maximum sum of a subarray of size exactly k, and the sum of the best circular subarray (wrapping allowed). python def…
- Problem: Maintain prefix sums under point updates with a Fenwick tree (1-indexed). cpp int n = 8; vector<long long> t(n + 1, 0); void…
- Problem: Range minimum queries with a sparse table after O(n log n) preprocessing. python a = [7, 2, 9, 4, 3, 8, 6, 1, 5] n = len(a); LOG…
- Problem: A segment tree stores range sums. How many nodes does the recursive query visit? python a = [1, 3, 5, 7, 9, 11, 13, 15] visits =…