Help in debugging the MO's algorithm code which is getting TLE (DECOPAIR)

I am trying to solve this problem and I came up with Mo’s algorithm solution but it is giving TLE. I saw many other AC solution but they looks quite similar. Can someone please help me fixing this?

My solution -

Edit: I got AC by seeing some people code which is basically a change in comparator function to sort. Here is the link to AC code: But I didn’t understand the trick. Can someone please explain me this trick or help me with some links?