I can't solve this problem using python. I tried many variations of my code but all of them give TLE for 2 test cases. In C++, this problem can be solved using multiset, I tried using dict, collections.Counter, list in python but all of them give TLE. I used stdin and stdout to read the input and output. The time limit is 1 sec and 2 test cases with n = 2⋅10^5, m = 2⋅10^5 pass while the other two don't. I tried searching for solutions but the solutions provided also gave TLE in both cpython and pypy.
These two codes gave the best and similar results. First, Second.