Reuse progress across sorted sequences
Merge, sweep offline queries, and filter with forward-moving indices.
Understand the idea
When two inputs are sorted, compare their next unused items and advance the side you consume. A merge never needs to restart a pointer. For threshold queries, sort queries with their original indices and advance one array pointer as the thresholds increase.
Trace a small example
Merging [1, 4, 8] and [2, 4, 7] produces [1, 2, 4, 4, 7, 8]. For values [1, 3, 3, 8] and thresholds 3, 0, 5, an offline sweep answers 3, 0, 3 after restoring the original query order. Stable filtering instead uses a read index and a write index, preserving accepted items in order.
Conditions and cost
Merging costs O(n + m). An offline sweep costs O(n + q) after sorting, plus the sort costs. Sorting is inappropriate when the original adjacency matters, such as contiguous subarrays.
What must accompany an offline query when queries are reordered?
Turn the idea into code
Count values ≤ each threshold 6, 2, 6 for the sorted array [2, 2, 5, 9].
Give me a hint
Equal queries can reuse the same pointer position.
Show the explained solution
The answers are 3, 2, 3. The pointer passes the two 2s, then 5, and never passes 9.
Your notes
Mark complete when you can explain it yourself.