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?
- A. Loop from l to r per query: O(q·n) worst case
- B. Segment tree: O(log n) per query is the only option
- C. Prefix sums: O(n) preprocessing and O(1) per query
- 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
- 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…
- 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?