If you have not seen already, DQUERY is a problem on SPOJ which asks us to query the number of distinct elements present in a range.
There are ways to solve it online, which might also be possible with what I'll be discussing today, but for sake of explanation we'll solve it offline.
Offline way to solve DQUERY involves use of Fenwick Trees, which is already a well-known technique but we'll try to formulate the solution ourselves in a much more intuitive way.
Let us forget about queries, assume we've a hypothetical $$$NxN$$$ grid $$$distinct$$$ where $$$distinct[i][j]$$$