hello @Himanshu-Jhawar-2273952536067590
editorial of problem is already available . u can check that.
for ur reference->
First observation we should make to be able to solve this problem: if two matrices have common subsquare of size X , they also have common subsquares of sizes X-1 , X-2 , X-3 ,… , 1 (you may simply take part of large subsquare).
This observation should make idea of using binary search here quite obvious. Now we need to learn how to check that given matrices have common subsquare of size X .
Quite a few of tests are small&random enough to give you points even for some naive checking - running over all squares in first matrix, comparing them with all squares in second matrix (you may add some smart breaks here etc.). However, this isn’t supposed to give you a full score.
First improvement is to learn how to compare two squares faster than with naive checking. Here hashing can help us.
Hashing will allow us to represent whole square as a single number , and compare two squares by comparing corresponding numbers.
Type “Rabin-Karp 2d” in Google and at the first page you’ll have several different guides/implementations for 2d version of Rabin-Karp algorithm . If you are completely new to all these things - start with 1d version of algorithm (where we are comparing substrings instead of subsquares ). After understanding 1d version - 2d version should be also pretty clear, because it is a simple generalization of 1d.
Now we have O(N^4) checker for particular value of X , which is still too slow (but much better than before). How to improve it even more? Instead of comparing our subsquare with every single subsquare from other matrix, we may compare it with all subsquares from that matrix at the same time. We are interested to know if there is a pair of equal subsquares; let’s put all subsquares of first matrix in a set . Now for every subsquare from second matrix we can check if it has a pair in first matrix, by simply looking at our set . It gives us logN instead of N^2 here.
Now we have some sort of proper solution. Time limit isn’t very strict; however, if you are actually going to use sets, it may be too slow . Instead you may store all values in sorted vector and use std::lower_bound() to check that some value is presented there. Also you may get rid of any % operations by doing all calculations modulo 2^64 (yes, there were no anti-hash tests in data set
) Such solution should get full score without any problems.