This problem as E problem for the contest. For this problem, while going through comments I found ankan2526 a alternative and easy solution by randomly picking an index, swapping it with index of x and checking if this swap is an answer. But I didn't understand why will this algorithm halt or even give an AC in 2s. I applied the same concept but got a TLE. My submission.
Please tell where I got wrong, and how ankan2526 works perfectly. Also, please comment any good links for learning the complexity analysis of such algorithms.