Data Structures & AlgorithmsHardGoogle · Flipkart interview
An analytics service holds a static array of n = 10⁵ integers and must answer q = 10⁶ queries 'minimum of a[l..r]' as fast as possible. Which structure gives the best total time?
- A. Prefix-minimum array: O(n) build, O(1) per query
- B. Segment tree: O(n) build, O(log n) per query, which is optimal for static data
- C. Sqrt decomposition: O(n) build, O(1) per query
- D. Sparse table: O(n log n) build, O(1) per query using two overlapping power-of-two blocks
Correct answer: D. Sparse table: O(n log n) build, O(1) per query using two overlapping power-of-two blocks
Minimum is idempotent, so two overlapping blocks of length 2^k cover [l, r] and the sparse table answers in O(1): about 1.7 × 10⁶ build steps plus 10⁶ queries. Prefix minima only work for ranges starting at 0, and sqrt decomposition costs O(√n) per query; a segment tree works but adds a log factor.
More Coding Interview Problems questions
- Given n = 5 × 10⁴ integers, count pairs i < j with a[i] > 2·a[j]. Which approach is correct and efficient?
- Problem: Evaluate a reverse-Polish expression. The specification says division must truncate toward zero (as in C or Java). python def…
- Problem: Sum the minimum of every contiguous subarray using a monotonic stack (previous-less and next-less-or-equal boundaries). python…
- Problem: Count the distinct non-empty substrings of a short string. python s = "ababa" print(len({s[i:j] for i in range(len(s)) for j in…
- Problem: Compute the KMP prefix function (pi[i] = length of the longest proper prefix of s[0..i] that is also its suffix). python def…
- Problem: Compute the Z-array (z[i] = length of the longest substring starting at i that matches a prefix of s; z[0] is set to 0). python…