Data Structures19 sections · 729 units
Open in Course

Challenge: Multiple Values

Top-k in a range

Given an array, answer queries: what are the kk smallest values in range [l,r][l, r]? Sparse table for min gives only the smallest. For top-kk, you need more storage.

Approach: at each st[i][j]\text{st}[i][j], store the kk smallest values in that range. Merge by combining two sorted lists and keeping the smallest kk. Space: O(nklogn)O(nk \log n).

Build: O(nklogn)O(nk \log n). Query: O(k)O(k). This works when kk is small and fixed. For variable kk, consider other structures like wavelet trees.