TLE in FCTRE Python3 in last subtask

Continuing the discussion from FCTRE - Editorial:
Solution link : CodeChef: Practical coding for everyone
Can someone pls help me with my code. I m getting TLE on the last subtasks. I am unable to figure out the problem. Is my way of sorting queries fine ? Any help will be appreciated