Working perfectly in O(nlogn) for all test cases!