Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

n = 10⁵ points are given, followed by q = 10⁵ OFFLINE queries 'how many points lie in the axis-aligned rectangle [x1, x2] × [y1, y2]?'. Which approach answers all queries within about O((n + q) log n)?

  1. A. A 2-D prefix-sum array over the coordinate range
  2. B. A k-d tree, which guarantees O(log n) per query
  3. C. An offline sweep over x with a Fenwick tree on compressed y, four prefix counts per query
  4. D. Sort points by x and binary search each query's x-range only

Correct answer: C. An offline sweep over x with a Fenwick tree on compressed y, four prefix counts per query

A sweep over x with a BIT on y answers 'points with x ≤ X and y ≤ Y' in O(log n), and inclusion–exclusion combines four such counts. A 2-D prefix array needs memory proportional to the coordinate range (often 10⁹ × 10⁹ cells); a k-d tree gives O(√n) per rectangle query; filtering only by x leaves an O(n) scan.

More Coding Interview Problems questions

Exams that ask this topic