How to solve query type problems

whats the way to approach query problems like these:
https://hack.codingblocks.com/app/contests/1238/401/problem
https://hack.codingblocks.com/app/contests/1238/708/problem