I am writing now a task for which you need to be able to quickly find the largest common prefix of two lines.
I decided to do this using a binary search: we look through the length of the prefix and if the hash of this prefix for two lines is the same, then we move the borders to the right to find the greater length of the prefix, and otherwise we move to the left to see the smaller length of the prefix.
The polynomial hash just allows you to find the hash of the entire string first, and then find the hash of the substring after O (1), which is convenient for comparing these very substrings.
But there is a problem: for some reason, my binary search finds the wrong prefix length and I can’t find it out.
What is the problem?
Prefix search:
int d(string &a, string &b) { StrHash ha(a), hb(b); int mid, l = 0, r = min(a.size(), b.size()) - 1; while(l < r) { mid = (l + r) / 2; if(ha.get(0, mid) == hb.get(0, mid)) { l = mid + 1; } else { r = mid - 1; } } int common; ///А тут мы проверяем, нашли мы префикс или нет. if(ha.get(0, l) == hb.get(0, l)) common = l + 1; else common = 0; return common; } A test with a bug that finds the answer 0 :
s1 = 'aaaaa' s2 = 'ab'