This was the Problem E for Codeforces Round 935. For this problem, while going through comments I found ankan2526 has 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 this submission works perfectly fine. Also, please comment any good links for learning the complexity analysis of such algorithms.