Sort the questions first
transcript
Twenty thousand range questions. Each one asks about a range. Sort them before you answer.
In the given order, the window moves over 212,810,043 steps. In sorted order, it moves 2,381,624 steps. The answers are the same.
Cut the log into blocks. Group the questions by the block of the left end. Inside a block, sort by the right end.
Block three, seven questions. Block zero goes up. Block one goes down. Block two goes up.
Start the window empty. Right at zero claims position zero. Right at minus one is empty.
Questions in one block have close left ends. So the left pointer moves less than a block. The right pointer sweeps once for each block. That keeps the total number of steps small.
The block size is n over the square root of q. For twenty thousand each, that is 141. Never let the block be zero.
Answer them in a smart order. The window then moves little. Full breakdown in the lecture.