Data Structures & AlgorithmsHardAmazon · Microsoft OA
A binary counter starts at 0 and is incremented n times; each increment flips trailing 1s to 0 and one 0 to 1. What is the total number of bit flips?
- A. Θ(n log n), since each increment can flip log n bits
- B. Less than 2n, so O(1) amortised per increment
- C. Exactly n
- D. Θ(n²)
Correct answer: B. Less than 2n, so O(1) amortised per increment
Bit i flips every 2ⁱ increments, so the total is Σ n/2ⁱ < 2n. A single increment like 0111…1 → 1000…0 is expensive, but such increments are rare.
More Coding Interview Problems questions
- A service must detect whether a dependency graph with 10⁵ modules and 10⁶ edges has a cycle. Which approach is both correct and efficient?
- Shortest paths in a large grid where each move costs either 0 or 1. Which algorithm is the most efficient correct choice?
- You must report the 100 largest values from a stream of 10⁹ integers using about 1 MB of memory. Which approach fits?
- Edge case: JavaScript type coercion. javascript console.log(typeof null, [] + {}, [] == ![], 0.1 + 0.2 === 0.3); What is printed?
- Edge case: += versus + on a list that has another name. python a = [1, 2, 3] b = a a += [4] a = a + [5] print(b, a) What is printed?
- Edge case: changing a dict while iterating over it. python d = {1: 'a', 2: 'b', 3: 'c'} try: for k in d: if k == 2: d[4] = 'd' print("ok"…