You are given a string and a word, your task is that count the number of the occurrences of the given word in the string.
This was the signature of the function:
public int countOccurences(String str, String word) {}I was able to figure out a simple solution O(str.length * word.length).
But the interviewer asked me if I can somehow prepare the strings (complexity for this operation ignored), so that the count would take constant time.
He was giving me a lot of tipps but I still was not able to figure out the solution.
I am not sure if I understood the tipps correctly, but I think the interviewer wanted to encode the strings as numbers and then by doing some arithmetical operation(s) count the occurrences.
I haven't solved the problem from this interview even conceptually, but I did good in other 3 interviews and still got the offer.
Any idea how to solve this problem?
Thank you in advance