Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Answer q = 10⁵ queries 'sum of a[l..r]' on a static array of n = 10⁵ values. Which approach is best?

  1. A. Loop from l to r per query: O(q·n) worst case
  2. B. Segment tree: O(log n) per query is the only option
  3. C. Prefix sums: O(n) preprocessing and O(1) per query
  4. D. Sort the array and binary search l and r

Correct answer: C. Prefix sums: O(n) preprocessing and O(1) per query

Without updates, P[r + 1] − P[l] answers each query instantly. The loop is up to 10¹⁰ operations. A segment tree or Fenwick tree is needed only when values also change between queries. Sorting destroys positions.

More Coding Interview Problems questions

Exams that ask this topic