iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📚

Learning Rolling Hash through University of Tokyo Graduate School Entrance Exams

に公開

I will introduce the Rolling Hash algorithm[1] used in string searching, based on an entrance exam question for the University of Tokyo's Graduate School (Graduate School of Information Science and Technology, Department of Computer Science, FY2020 Specialized Subject I, Question 3).
The PDF of the problem is available below. [2]

https://www.i.u-tokyo.ac.jp/edu/course/cs/pdf/2020computer-s1.pdf#page=6

Although this problem is themed around Rolling Hash, it is designed to be solvable even if you don't know the algorithm beforehand; rather, you can understand Rolling Hash through this problem. In that sense, it is a very educational question and, I believe, a beneficial one for those who want to learn about Rolling Hash from now on. [3]

Now, let's look at the problem.

Problem Statement [1]


Many symbols have appeared. Let's organize them.

Regarding string s
Length of s: l(s)
The i-th character of s: s[i]
The string obtained by removing the first i characters of s: s + i \ (0 \leq i < l(s))

Regarding character c
A function that maps c to a positive integer less than or equal to N: numval(c)
(For example, you can imagine character codes.)

Also, let's read the description of the FIND problem. This is an explanation of string searching. For example, if s = \mathrm{PROBLEM}, p = \mathrm{OBL}:

PROBLEM
OBL

No match

PROBLEM
 OBL

No match

PROBLEM
  OBL

Match!

In the case of a match,

s[2 + 0] = p[0] = \mathrm{O} \\ s[2 + 1] = p[1] = \mathrm{B} \\ s[2 + 2] = p[2] = \mathrm{L}

and i = 2 becomes the solution for FIND in this case.
If p = \mathrm{OBE}, it doesn't match anywhere in s = \mathrm{PROBLEM}, so i = -1 is the solution.

Problem Statement [2]


Now, an algorithm S to solve the FIND problem has been presented. Let's think about what this algorithm is doing.
Inside the for-loop, a function called eq(s+i, p) is called every time until it returns 1. Reading the problem statement, we can see that eq(s+i, p) is a function that returns 1 if the first l(p) characters of s+i match p.
Here, s+i was the string obtained by removing the first i characters of s. In other words, algorithm S follows this flow:

Compare the string obtained by removing the first 0 characters of s with p....
Compare the string obtained by removing the first 1 characters of s with p....
Compare the string obtained by removing the first 2 characters of s with p....

We can see that this is the same brute-force search as before:

PROBLEM
OBL

No match

PROBLEM
 OBL

No match

PROBLEM
  OBL

Match!

Problem Statement [3]


(1) is a problem to find the worst-case computational complexity of algorithm S. The most time-consuming case is, of course, when p does not match anywhere in s and the for-loop runs to the end.
From the beginning of the problem statement, one string comparison eq(s+i, p) takes O(l(p)) time complexity. The number of loop iterations in the for-loop is l(s) - l(p) + 1, which is O(l(s) - l(p)) in big O notation. Therefore, the overall complexity is:

O\bigg(l(p)(l(s) - l(p))\bigg)

(I feel it's also acceptable to write it as O(l(s)l(p))).

Problem Statement [4]


Finally, the hash appeared.
It might be hard to understand the original formula just by looking at it, so let's first think about it with a concrete example. Let s = \mathrm{ABCDEF}. Also, let's set:

numval(A) = 1 \\ numval(B) = 2 \\ numval(C) = 3 \\ ...

To make it easier to visualize, let's consider the case where m = 4. The above formula can be expanded as follows:

h(s, 4) \\ = \Bigg( numval(s[0]) \cdot d^3 + numval(s[1]) \cdot d^2 + numval(s[2]) \cdot d^1 + numval(s[3]) \Bigg) \mod q \\ = \Bigg( 1 \cdot d^3 + 2 \cdot d^2 + 3 \cdot d^1 + 4 \Bigg) \mod q \\

For example, if we set d=3, q=10:

( 1 \cdot 3^3 + 2 \cdot 3^2 + 3 \cdot 3^1 + 4 ) \mod 10 = 8

Right?

Problem Statement [5]


(2) asks how to find h(s+i+1, m) from h(s+i, m). Let's organize and think about the formula.
s+i was the string obtained by removing the first i characters of s, so this is about finding the hash of the first m characters of the string obtained by removing the first i+1 characters of s from the hash of the first m characters of the string obtained by removing the first i characters of s. Furthermore, this needs to be solvable in O(1).
Looking back at the initial settings in the problem statement, the operations that can be done in O(1) are:

  • The operation to find s+i from s and i
  • The operation to find numval(c) from c
  • Addition, multiplication, and modulo operations of integers

Now, let's look back at the concrete example from earlier.

h(s, 4) \\ = \Bigg( numval(s[0]) \cdot d^3 + numval(s[1]) \cdot d^2 + numval(s[2]) \cdot d^1 + numval(s[3]) \Bigg) \mod q

From here, h(s + 1, 4) must be calculable in O(1).

h(s + 1, 4) \\ = \Bigg( numval((s + 1)[0]) \cdot d^3 + numval((s + 1)[1]) \cdot d^2 + \\ numval((s + 1)[2]) \cdot d^1 + numval((s + 1)[3]) \Bigg) \mod q

Furthermore, since s + 1 is the string with the first character of s removed, for example, (s + 1)[0] = s[1]. Keeping this in mind,

h(s + 1, 4) \\ = \Bigg( numval(s[1]) \cdot d^3 + numval(s[2]) \cdot d^2 + numval(s[3]) \cdot d^1 + numval(s[4]) \Bigg) \mod q

By this point, you might notice that the form of h(s + 1, 4) is almost the same as h(s, 4).
Since addition, subtraction, and multiplication are closed under modulo[4], to find h(s + 1, 4) from h(s, 4), you can:

  • Subtract numval(s[0]) \cdot d^3 from h(s, 4),
  • Multiply it by d,
  • Add numval(s[4]) to it,
  • And finally take \mod q

This operation works.

For the general case:

h(s + i, m) \\ = \Bigg( numval((s+i)[0]) \cdot d^{m-1} + numval((s+i)[1]) \cdot d^{m-2} + \\ ... + numval((s+i)[m-1]) \Bigg) \mod q \\ = \Bigg( numval(s[i]) \cdot d^{m-1} + numval(s[i+1]) \cdot d^{m-2} + \\ ... + numval(s[i+m-1]) \Bigg) \mod q

You can find h(s + i + 1, m) with these steps:

  • Subtract numval(s[i]) \cdot d^{m-1} = numval(s[i]) \cdot d_m from h' = h(s + i, m),
  • Multiply it by d,
  • Add numval(s[i+m]) to it,
  • And finally take \mod q

In pseudo-code, it would look like this:

tmp = numval(s[i]);
tmp = tmp * d_m;
ans = h' + tmp * (-1);
ans = ans * d;
ans = ans + numval(s[i+m]);
ans = ans % q;
return ans;

Since numval(), +, *, and % can be done in O(1), this is correct.

Problem Statement [6]


Now, (3) is a problem about considering the string search algorithm using rolling hash, which is the main topic. Note that two questions are given.

First, regarding the first half of the problem, let's think about using the hint from (2). h(s+i, l(p)) refers to the hash value of the first l(p) characters of the string obtained by removing the first i characters of s, but there is no need to calculate this individually for each i. If you calculate h(s, l(p)), you can find h(s + 1, l(p)) in O(1), then find h(s + 2, l(p)) in O(1), and so on.

Therefore, a pseudo-code for an algorithm to find the smallest non-negative integer i such that h(p, l(p)) = h(s+i, l(p)) would look like this:

Precompute h(p, l(p))
Precompute h(s, l(p))
Precompute d_l(p)

if (h(p, l(p)) == h(s, l(p)))
  return 0;

for (i = 0; i <= l(s)-l(p)-1; i++) 
  Calculate h(s+i+1, l(p)) in O(1) from h(s+i, l(p)) and d_l(p)
  
  if (h(p, l(p)) == h(s+i+1, l(p)))
    return i+1;
    
return -1;

Since hashes are just integer values, comparing hashes can naturally be done in O(1). Therefore, the computational complexity of the for-loop part is O(l(s)-l(p)).
What remains is to analyze the complexity of these parts:

  • Precomputing h(p, l(p))
  • Precomputing h(s, l(p))
  • Precomputing d_{l(p)} = d^{l(p) - 1}

First, since multiplication can be done in O(1), it is obvious that d_{l(p)} = d^{l(p) - 1} can be calculated in O(l(p)).
Also, the hash of a string of l(p) characters can be calculated in O(l(p)) by alternately repeating addition and multiplication. For example, h(s, l(p)) is found like this:

ans = numval(s[0]);
for (i = 1; i <= l(p)-1; i++)
  ans = ans * d;
  ans = ans + numval(s[i]);
ans = ans % q;
return ans;

The calculation for h(p, l(p)) can be done similarly.

Based on the above, the complexity for the parts outside the for-loop is O(l(p)), and we can say that the complexity for the entire process is O(l(s) + l(p)). Thus, this is the algorithm H_0 we need to find.

Next, for the second half of the problem, it's something you can understand with a little thought. For this algorithm H_0 to solve the FIND problem, it is assumed that "matching hash values imply matching strings," or in other words, "different strings correspond to different integer hash values."
Conversely, if different strings correspond to the same hash value, the premise breaks down. As an extreme example, if you set the modulo q to q = 1, the hash value of any string becomes 0, so any strings would be considered the same. In this case, algorithm H_0 cannot possibly solve the FIND problem.
Therefore, as an answer to this question, something like "When hash collisions occur" would be sufficient. [5]

As long as hashes do not collide, algorithm H_0 can solve the FIND problem. And while algorithm S was O(l(s)l(p)), algorithm H_0 is O(l(s) + l(p)), so it is indeed faster!
For example, if l(s) = 10^7 and l(p) = 10^3, the former is roughly 10^{10}, while the latter can be estimated at roughly 10^7.


What did you think? We were able to learn comprehensively about the rolling hash algorithm, its computational complexity, and the hash collision problem.
I think this problem is around the easy to standard difficulty level[6][7] among the past questions for the Computer Science major, so if you thought "This is easy!", please try applying to the Department of Computer Science, Graduate School of Information Science and Technology, at the University of Tokyo!

脚注
  1. To be precise, the official name of the string search algorithm introduced here is the Rabin-Karp algorithm, and Rolling Hash refers to the hash used in the Rabin-Karp algorithm, but in this article, I will use "Rolling Hash" as a shorthand for the algorithm itself. ↩︎

  2. The PDF of past questions might have been made private and become unavailable; in that case, please try searching with archival tools like archive.org. ↩︎

  3. Of course, for those who already know Rolling Hash through competitive programming or other means, solving this problem on an entrance exam would have been quite easy. I passed this department this year, but I didn't know about Rolling Hash until I solved this past question... By the way, those applying to the Department of Computer Science should also master other string search algorithms like KMP and BM. ↩︎

  4. To have an intuitive feel for this, I feel you might need experience in competitive programming calculating remainders divided by 1,000,000,007... ↩︎

  5. In the world of competitive programming, it is said that setting the Mod to 2^{61} - 1 is safe. Reference: https://qiita.com/keymoon/items/11fac5627672a6d6a9f6 ↩︎

  6. Actually, there is one more small question after this, but I omitted it as it deviates slightly from the introduction to Rolling Hash. ↩︎

  7. However, problems with such a strong competitive programming flavor are only part of the exam; the entrance exam as a whole covers a wide range of fields from "Information Mathematics, Numerical Analysis, Discrete Mathematics, Algorithms and Complexity, Formal Languages, Logic, Programming Language Theory, Computer Architecture, Operating Systems, Digital Circuits, and Machine Learning." Based on my view as someone who passed, you don't need to solve extremely difficult problems; you should be fine as long as you can correctly answer basic questions in any field. ↩︎

Discussion