Thanks @rishup_nitdgp for such a good question and also @akashbhalotia for such a great editorial !!
My unnecessary story for the question :
I finally solved this problem and I believe that I have got a basic understanding of string hashing. I still am having a few doubts regarding this topic - string hashing.
Firstly I was checking for collisions in my code so I got TLE. So my hope for solving this question got smashed . So I started looking for other people’s code and then I realised that they weren’t checking for collisions, so I commented that part in my code and it got accepted .
So basically I want to know whether or not should we check for collision and if yes then when should we and how can one make checking collisions more effective ?
Also can anyone please answer this question also ? It’s regarding the Chef Impress question in this month’s cook off. It will be great help for beginners like me.
@rishup_nitdgp@akashbhalotia hello sir after reading your editorial I tried to do this question but it got TLE can you please have a look at my solution and explain me where I do something wrong. Any suggestions are welcome sir.
KIndly reply after seeing the comment. It will help me to improve me.
I used hashing creates a hash function and if the value of pairs of the hash function is equal then it is a match.
can someone explain to me why I’m getting TLE?
dd={}
modulo=10**9+7
for i in range(97,123):
dd[chr(i)]=i-97+1
def search(pattern,text):
n=len(pattern)
c=0
e=0
for j in range(n):
a=dd[pattern[j]]
b=dd[text[j]]
c+=(a*(10**(n-j-1)))%modulo
e+=(b*(10**(n-j-1)))%modulo
return c==e
for _ in range(int(input())):
s=input()
n=len(s)
co=0
if n<4:
print("0")
else:
for i in range(2,n,2):
a=s[:i//2]
b=s[i//2:i]
c=s[i:(i+n)//2]
d=s[(i+n)//2:]
if search(a,b) and search(c,d):
co+=1
print(co)
I read about string-hashing on cp-algorithms according to which: hash(i,j) = (hash(0,j)-hash(0,i-1))*(multiplicative modulo inverse of p^i)
and have used this in my solution.
If my WA solution is difficult to understand, I have commented my code in case here: https://ideone.com/SSDjRD
@abhishek_iiita I also tried to implement the solution using kmp algorithm, but without any extra lps array and period. Can you explain why the period is calculated for the substring?
I used the similar approach as yours for calculating the 2 lps arrays. While iterating over the original string I just checked the length of lps for two halves and if the they exceed the half lengths then I increment the count. Still getting a WA.