Read more about range queries and data structures used for solving them here.