I am getting TLE in the question. Please help me with this. Here is the solution.
your solution is \mathcal{O(N+ \sqrt N)} per test-case which is too slow for this problem.