In the recently concluded Long challenge, in the problem "CLONEME", I wrote an optimal brute force solution. The solution is as follows :
- I stored the prefix sum, sum of square and sum of cubes of elements in an array.
- Check if the 2 subarrays are permutation of each other or not. For this simply check if the sum, sum of squares, sum of cubes etc are exactly same are not.
- Now, we need to deal with one mismatch only. Now, I found the difference of sum and sum of sqaures of 2 subarrays. If only one element mismatches(let them be $a$ and $b$, then we have the following equations :
$S_1 - S_2 = a - b$ and ${S_1}^2 - {S_2}^2 = a^2 - b^2$.
Then $a + b = \frac{{S_1}^2 - {S_2}^2}{S_1 - S_2}$ i.e. ${S_1}^2 - {S_2}^2$ should be divisble by $S_1 - S_2$.
Also, if $S_1 == S_2$, this means atleast 2 elements differ as, there not permutation as assured by the prefix sums checked above.
Now, using difference in sum of cubes in the 2 subarrays, I confirm again if the 2 elements I found are valid out. i.e if the difference of the sum of cubes of 2 subarrays is exactly equal to the difference of the cube of the 2 numbers found.
If all the above methods fails, I simply do a brute force algorithm, i.e. construct the 2 subarrays, sort them and then check if they mismatch at one position only.
I had tried to construct test cases such that my solution TLE, but was unsuccessful. Can someone here would like to challenge my solution for the problem ?
Remember, that almost all the queries should be different as I should cache the previous queries answer which is generally used and such test cases are avoided by making problem. (i.e. if you find a particluar query for which my solution will execute the brute force solution, then do not give the same query again and again in the test case).
Happy coding :)