Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: An array of n = 10⁵ values receives 10⁵ operations, each either 'add v to a[i]' or 'sum of a[l..r]'. Which data structure gives O(log n) for both operations?
- A. Prefix-sum array rebuilt after every update
- B. Fenwick tree (binary indexed tree) or segment tree
- C. Sparse table
- D. Hash map from index to value
Correct answer: B. Fenwick tree (binary indexed tree) or segment tree
Rebuilding prefix sums is O(n) per update (10¹⁰ total). A sparse table answers idempotent queries (min/max) in O(1) but cannot be updated cheaply and does not handle sums with overlap. A Fenwick tree updates and queries prefix sums in O(log n).
More Coding Interview Problems questions
- Problem: n ≤ 18 cities, find the shortest route visiting every city exactly once (travelling salesman). Which approach fits?
- Problem: n = 10⁵ intervals; for each, count how many other intervals it overlaps. What is the best complexity?
- Problem: A function does for i in range(n): for j in range(i, n, i + 1): work(). What is its time complexity?
- Problem: A recursive function on n does O(1) work and makes two calls on n/2. What is T(n)?
- Problem: Inside a loop of n iterations, the code calls Python's list.pop(0) and Java's String +=. What is the real complexity of the loop?
- Problem: For n = 10⁶ distinct integers up to 10⁹, find the smallest positive integer missing from the array in O(n) time and O(1) extra…