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?

  1. A. Prefix-sum array rebuilt after every update
  2. B. Fenwick tree (binary indexed tree) or segment tree
  3. C. Sparse table
  4. 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

Exams that ask this topic