Skip to content

Rabin-Karp

words

Level 2 of 3

Also called Karp-Rabin algorithm and Rolling hash search.

how it works

The idea on the watch page's first example, roo in kangaroo. Then the whole method on it, step by step.

Look for roo in kangaroo. Read each letter as a number, a as 1 up to z as 26. As 345 is 3 hundreds, 4 tens and 5 ones, roo is 18 lots of 676 (26 times 26), 15 lots of 26 and 15 ones: 12,573. That is 11 times 1,143 exactly, so divided by 11 it leaves 0. That remainder is roo's fingerprint. Each place gets the fingerprint of the 3 letters above it. The same letters always give the same fingerprint, so where it is not 0, those letters cannot be roo, and none is compared. At place 3, nga leaves 0 too, by chance: n is not r, 1 comparison. At place 6, r, o and o all match, so roo stands at place 6. Each fingerprint comes from the one before: the roll. kan is 7,476. Take off k's part, 11 times 676, which is 7,436: 40 is left. Times 26 makes every letter's worth 26 times bigger, as times 10 turns 34 into 340: 1,040. Add g's 7: ang, 1,047, which leaves 2. 7 fingerprints and 4 comparisons make 11 steps. Rabin-Karp keeps only the remainders; the last table shows they end on the same 2.

letternumberworthpart
r1867612,168
o1526390
o15115
roo12,573, which leaves 0
roo in base 26. From the right the worths are 1, 26 and 676, each 26 times the last, as 345's are 1, 10 and 100.
placeletters abovefingerprintcomparisons
1kan70
2ang20
3nga01, by chance
4gar20
5aro40
6roo03, a match
all7: 6 places and roo's4
roo's fingerprint is 0. Letters are compared only where a place's is 0 too, by chance at place 3 and in a match at place 6.
movenumberremainder
kan7,4767
take off k's 11 times 676, which leaves 0407
times 261,0406
add g's 71,047, ang2
The roll from kan to ang, on the whole number and on its remainder alone. Both end on 2.
A fingerprint that agrees by chance: 7 moments of its 21 steps, the steps between them left for the watch page
  1. step 2 of 21

    kangarooroo123456

    roo read as a number in base 26 leaves 0 when divided by 11: that is the pattern's fingerprint.

    what it remembers to know where it is
    pattern stands at place
    1
    pattern's fingerprint
    0
    fingerprint here
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 4 of 21

    kangarooroo1234567

    The fingerprint here is 7, not 0, so these letters cannot be the pattern. Compare none.

    what it remembers to know where it is
    pattern stands at place
    1
    pattern's fingerprint
    0
    fingerprint here
    7

    watch from here

  3. step 5 of 21

    kangarooroo12345672

    Move the pattern on to place 2. Take k off the front of the fingerprint and add g at the end, giving 2.

    what it remembers to know where it is
    pattern stands at place
    2
    pattern's fingerprint
    0
    fingerprint here
    2

    watch from here

  4. step 9 of 21

    kangarooroo123456720

    The text's n at position 3 is not the pattern's r.

    what it remembers to know where it is
    pattern stands at place
    3
    pattern's fingerprint
    0
    fingerprint here
    0

    watch from here

  5. step 10 of 21

    kangarooroo123456720

    The fingerprint agreed by chance at place 3, but the letters do not.

    what it remembers to know where it is
    pattern stands at place
    3
    pattern's fingerprint
    0
    fingerprint here
    0

    watch from here

  6. step 20 of 21

    kangarooroo123456720240

    Every letter agrees: the pattern stands at place 6. Mark it.

    what it remembers to know where it is
    pattern stands at place
    6
    pattern's fingerprint
    0
    fingerprint here
    0

    watch from here

  7. step 21 of 21

    kangarooroo123456720240

    Every place has been tried. The pattern stands at 1 place. That took 7 fingerprints and 4 comparisons.

    what it remembers to know where it is
    pattern stands at place
    6
    pattern's fingerprint
    0
    fingerprint here
    0

    watch from here

the steps, in plain words
  1. work out the pattern's fingerprint: its letters as a number in base 26, the remainder after dividing by 11Python lines 14 and 15
  2. for each place the pattern can stand, from the first, take the fingerprint of the text under it, the first worked out the same wayPython lines 16 and 18
  3. where the fingerprints differ, the letters cannot match, so compare nonePython lines 22 and 23
  4. where they agree, compare the letters to be sure, and mark a match if every one agreesPython lines 24, 25, 26, 27 and 28
  5. move the pattern on one place: take off the letter leaving and add the letter arrivingPython lines 19, 20 and 21
  6. every place tried, so every match is foundPython line 29
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def rabin_karp(text, pattern):
    """Find every place a pattern stands in a text, comparing fingerprints
    before letters.

    text and pattern are each a run of letters a to z, the pattern no longer
    than the text. Returns the places it stands, counted from 0.
    """
    def value(letter):  # a is 1, b is 2, and so on up to z, 26
        return ord(letter) - 96

    n, m = len(text), len(pattern)
    high = 26 ** (m - 1) % 11  # what the first letter's place is worth
    want = here = 0
    for k in range(m):  # the pattern's fingerprint, and the first place's
        want = (want * 26 + value(pattern[k])) % 11
        here = (here * 26 + value(text[k])) % 11
    places = []
    for place in range(n - m + 1):  # each place the pattern can stand
        if place > 0:  # move on: take off the letter leaving, add the one arriving
            leaving, arriving = text[place - 1], text[place + m - 1]
            here = ((here - value(leaving) * high) * 26 + value(arriving)) % 11
        if here != want:  # the fingerprints differ: these letters cannot match
            continue  # so compare none
        matched = 0  # they agree: compare the letters to be sure
        while matched < m and text[place + matched] == pattern[matched]:
            matched += 1
        if matched == m:  # every letter matched
            places.append(place)  # so it stands here
    return places  # every place tried: every match found

how it scales

The plot counts steps, each a fingerprint worked out or a comparison, on a text of nn letters and a pattern half as long, rounded up. In the best case, a's against a's ending in b, no place agrees, so no letter is compared. In the worst, a's against a's, every place agrees and matches. Measured from 10 to 10,000.

Each mark across or up is ten times the one before. The best line climbs one mark up for each mark across: 52 steps at 100 letters, 502 at 1,000. The worst climbs two marks up for each mark across: 2,602 at 100, 251,002 at 1,000. Ten times the letters, about 100 times the steps. Section 4 derives both.

fingerprints and comparisons, ten times more at each mark up

a seconda minutean houra dayslope 2102104106108101010121014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107

nn, how many letters the text has, ten times more at each mark to the right

  • a text of a's and a pattern of a's, half as longsolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
  • a text of a's and a pattern of a's ending in b, half as longsolid where measured by running it; dashed where its formula carries it on to ten million
how long the worst takes, at a billion steps a second
nnfingerprints and comparisonstime
1,000251,002about 251 microseconds
100,0002,500,100,002about 2.5 seconds
10,000,00025,000,010,000,002about 6.9 hours

The fingerprints and comparisons are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count Rabin-Karp's steps yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it makes a text of n
letters a and a pattern of half as many letters, rounded up, in two ways:
a's ending in one b, whose fingerprint never agrees with a place's, the
fewest; and all a, which agrees and matches at every place, the most. It
prints the steps for each, by count below: one for each fingerprint worked
out, and one for each letter of the text compared with a letter of the
pattern. The counts are the same on any computer; only the time differs.
"""


def rabin_karp(text, pattern):
    """Find every place a pattern stands in a text, comparing fingerprints
    before letters.

    text and pattern are each a run of letters a to z, the pattern no longer
    than the text. Returns the places it stands, counted from 0.
    """
    def value(letter):  # a is 1, b is 2, and so on up to z, 26
        return ord(letter) - 96

    n, m = len(text), len(pattern)
    high = 26 ** (m - 1) % 11  # what the first letter's place is worth
    want = here = 0
    for k in range(m):  # the pattern's fingerprint, and the first place's
        want = (want * 26 + value(pattern[k])) % 11
        here = (here * 26 + value(text[k])) % 11
    places = []
    for place in range(n - m + 1):  # each place the pattern can stand
        if place > 0:  # move on: take off the letter leaving, add the one arriving
            leaving, arriving = text[place - 1], text[place + m - 1]
            here = ((here - value(leaving) * high) * 26 + value(arriving)) % 11
        if here != want:  # the fingerprints differ: these letters cannot match
            continue  # so compare none
        matched = 0  # they agree: compare the letters to be sure
        while matched < m and text[place + matched] == pattern[matched]:
            matched += 1
        if matched == m:  # every letter matched
            places.append(place)  # so it stands here
    return places  # every place tried: every match found


def count(text, pattern):
    """How many steps rabin_karp takes: one for each fingerprint it works
    out, the pattern's and one for each place, and one for each letter of
    the text it compares with a letter of the pattern."""
    n, m = len(text), len(pattern)
    high = 26 ** (m - 1) % 11
    want = here = 0
    for k in range(m):
        want = (want * 26 + ord(pattern[k]) - 96) % 11
        here = (here * 26 + ord(text[k]) - 96) % 11
    steps = 2  # the pattern's fingerprint and the first place's
    for place in range(n - m + 1):
        if place > 0:
            leaving, arriving = ord(text[place - 1]) - 96, ord(text[place + m - 1]) - 96
            here = ((here - leaving * high) * 26 + arriving) % 11
            steps += 1  # this place's fingerprint
        if here != want:
            continue
        for k in range(m):
            steps += 1  # one comparison
            if text[place + k] != pattern[k]:
                break
    return steps


def cheapest(n):
    """A text of n a's and a pattern of half as many letters, rounded up,
    all a but the last, which is b."""
    return "a" * n, "a" * ((n + 1) // 2 - 1) + "b"


def dearest(n):
    """A text of n a's and a pattern of half as many a's, rounded up."""
    return "a" * n, "a" * ((n + 1) // 2)


if __name__ == "__main__":
    print(f"{'n':>7} {'a ending b':>11} {'all a':>10}")
    for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000):
        print(f"{n:>7} {count(*cheapest(n)):>11} {count(*dearest(n)):>10}")

best, worst and average

Here best and worst are texts and patterns of the same lengths, nn letters and ⌈n2⌉\lceil \frac{n}{2} \rceil. Section 4's question 3 shows that length costs the most. Both work out ⌊n2⌋+2\lfloor \frac{n}{2} \rfloor + 2 fingerprints, by section 4's question 1; only the comparisons differ. For 6 letters and 3: 5 fingerprints, then 0 comparisons at best and 12 at worst. No average is worked out.

A case is one kind of text and pattern. A bound says how fast its cost grows as letters are added.

The counts are in the grid below. A count is often made of pieces that grow at different speeds, and the fastest-growing piece swamps the rest. At 1,000 letters the worst is 251,002: 500 times 501 comparisons, which is 250,500, and 502 fingerprints. They grow about as n24\frac{n^2}{4} and n2\frac{n}{2}, and the first is nearly all of it. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
besta text of a's and a pattern of a's ending in b, half as longworsta text of a's and a pattern of a's, half as long
fingerprints worked out⌊n2⌋+2\lfloor \frac{n}{2} \rfloor + 2⌊n2⌋+2\lfloor \frac{n}{2} \rfloor + 2
letters compared0⌈n2⌉(⌊n2⌋+1)\lceil \frac{n}{2} \rceil (\lfloor \frac{n}{2} \rfloor + 1)
fingerprints and comparisons⌊n2⌋+2\lfloor \frac{n}{2} \rfloor + 2(⌈n2⌉+1)(⌊n2⌋+1)+1(\lceil \frac{n}{2} \rceil + 1)(\lfloor \frac{n}{2} \rfloor + 1) + 1
how the fingerprints and comparisons grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n2)\Theta(n^2)
ceiling, OOO(n)O(n)O(n2)O(n^2)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n2)\Omega(n^2)

extra memory: two fingerprints, the first letter's worth, the place and how many letters matched, beside the places found

Extra memory is the room it needs on top of the input itself, while it runs.

textpatternfingerprintscompared
kangarooroo74
bananaana56
pineapplekiwi70
aaaaaaaaaaaaaaa730
The watch page's four examples. No place of pineapple shares kiwi's fingerprint, so no letter is compared. The 10 a's match at every place.
nbestworst
6517
7521
10737
The two cases in steps, a pattern half the text, rounded up. At 10 letters the worst is the watch page's last example, 7 fingerprints and 30 comparisons.

where the formula comes from

Questions 1 and 2 count the steps, the plot's two lines. Question 3 shows why the pattern is half the text.

Question 1: how many steps, FF, on a text of nn a's and a pattern of a's ending in b, half as long, rounded up?
  1. the move: the places

    the line:
    places: n−m+1\begin{gathered} \text{places: } \\ n - m + 1 \end{gathered}

    why it is allowed: The pattern is first tried under the text's letter 1. At its last place, its last letter is under the text's last, nn, so its first is under letter n−m+1n - m + 1. For 6 letters and 3, places 1 to 4.

  2. the move: the fingerprints

    the line:
    fingerprints:n−m+2\begin{gathered} \text{fingerprints:} \\ n - m + 2 \end{gathered}

    why it is allowed: One for the pattern, then one for the letters above each place of line 1, whatever the letters are. For 6 letters and 3, 1 + 4, which is 5.

  3. the move: this page's pattern

    the line:
    the pattern’s letters:⌈n2⌉\begin{gathered} \text{the pattern's letters:} \\ \lceil \frac{n}{2} \rceil \end{gathered}

    why it is allowed: The cases take a pattern half as long as the text, rounded up, as its mm. Question 3 shows why. For 6, 3; for 7, 4.

  4. the move: no fingerprint agrees

    the line:
    a’s ending in b:0 comparisons\begin{gathered} \text{a's ending in b:} \\ 0 \text{ comparisons} \end{gathered}
    placeabovefingerprintcompared
    1aaa100
    2aaa100
    3aaa100
    4aaa100
    A text of 6 a's and the pattern aab. aaa is 703 and leaves 10; aab is 704 and leaves 0. No place agrees.

    why it is allowed: Every place has mm a's above it. The pattern's number is theirs plus 1, as its last letter is b (2) where theirs is a (1). Counting up by 1, the remainder goes up by 1, or from 10 back to 0, so it always changes. So no place agrees, and no letter is compared.

  5. the move: count the steps

    the line:
    F=n−⌈n2⌉+2F = n - \lceil \frac{n}{2} \rceil + 2

    why it is allowed: Put line 3's mm into line 2; by line 4, no comparison is added. For 6, 6 - 3 + 2, which is 5.

  6. the move: half, rounded down

    the line:
    F=⌊n2⌋+2F = \lfloor \frac{n}{2} \rfloor + 2

    why it is allowed: Half of nn rounded up and half of nn rounded down add up to nn. So nn less the first leaves the second. For 6, 3 and 3; for 7, 4 and 3.

  7. the move: a ceiling

    the line:
    F≤3nF \le 3n

    why it is allowed: Half of nn rounded down is at most nn, and from 1 up, 2 is at most 2n2n. Add the two. For 1, 2 against 3; for 6, 5 against 18.

  8. the move: read the bound

    the line:
    F∈O(n)F \in O(n)

    why it is allowed: By line 7, with the fixed multiple 3.

  9. the move: a floor

    the line:
    F≥n2F \ge \frac{n}{2}

    why it is allowed: Rounding down takes off less than 1, so line 6's ⌊n2⌋+2\lfloor \frac{n}{2} \rfloor + 2 is more than n2\frac{n}{2}. For 7, 5 against 3.5.

  10. the move: read the bound

    the line:
    F∈Ω(n)F \in \Omega(n)

    why it is allowed: By line 9, with the fixed multiple a half.

  11. the move: both together

    the line:
    F∈Θ(n)F \in \Theta(n)

    why it is allowed: Lines 8 and 10 bound FF by the same growth.

try it with a small nn: at n=6n = 6, line 5 gives F=5F = 5, which you can work out by hand

Question 2: how many steps, MM, on a text of nn a's and a pattern of a's half as long, rounded up?
  1. the move: a place's most

    the line:
    a place comparesat most m letters\begin{gathered} \text{a place compares} \\ \text{at most } m \text{ letters} \end{gathered}

    why it is allowed: Letters are compared only where the fingerprints agree, from the left, until one differs. The pattern has mm letters, so at most mm.

  2. the move: every place agrees and matches

    the line:
    a’s against a’s:m at every place\begin{gathered} \text{a's against a's:} \\ m \text{ at every place} \end{gathered}
    placeabovefingerprintcompared
    1aaa103
    2aaa103
    3aaa103
    4aaa103
    all5: 4 places and aaa's12
    A text of 6 a's and the pattern aaa. Every fingerprint is 10, and every place is a match. 5 fingerprints and 12 comparisons.

    why it is allowed: Every place has mm a's above it, the pattern's own letters, so its fingerprint too. Every place agrees, and all mm letters match.

  3. the move: multiply by the places

    the line:
    comparisons:⌈n2⌉(⌊n2⌋+1)\begin{gathered} \text{comparisons:} \\ \lceil \frac{n}{2} \rceil (\lfloor \frac{n}{2} \rfloor + 1) \end{gathered}

    why it is allowed: Section 4's question 1, lines 1, 3 and 6, give ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1 places. This question's line 2 gives ⌈n2⌉\lceil \frac{n}{2} \rceil comparisons at each. For 6, 4 times 3, which is 12.

  4. the move: add the fingerprints

    the line:
    M=⌊n2⌋+2+⌈n2⌉(⌊n2⌋+1)\begin{gathered} M = \lfloor \frac{n}{2} \rfloor + 2 \\ + \lceil \frac{n}{2} \rceil (\lfloor \frac{n}{2} \rfloor + 1) \end{gathered}

    why it is allowed: A step is a fingerprint or a comparison. Section 4's question 1, lines 2, 3 and 6, give ⌊n2⌋+2\lfloor \frac{n}{2} \rfloor + 2 fingerprints, whatever the letters. For 6, 5 + 12, which is 17; for 7, 5 + 16, which is 21.

  5. the move: gather the places

    the line:
    M=(⌈n2⌉+1)(⌊n2⌋+1)+1M = (\lceil \frac{n}{2} \rceil + 1)(\lfloor \frac{n}{2} \rfloor + 1) + 1

    why it is allowed: Line 4's ⌊n2⌋+2\lfloor \frac{n}{2} \rfloor + 2 is the places, ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1, plus 1. The places taken ⌈n2⌉\lceil \frac{n}{2} \rceil times and once more make ⌈n2⌉+1\lceil \frac{n}{2} \rceil + 1 times, and the 1 stays. For 7, 5 + 16 is 4 + 1 + 4 times 4, which is 4 times 5, plus 1, 21.

  6. the move: a ceiling

    the line:
    M≤3n2M \le 3n^2

    why it is allowed: From 1 up, half of nn rounded up is at most nn, so plus 1 at most 2n2n. Half rounded down is a whole number below nn, so plus 1 at most nn. Their product is at most twice n2n^2, and the last 1 at most n2n^2. For 6, 17 against 108.

  7. the move: read the bound

    the line:
    M∈O(n2)M \in O(n^2)

    why it is allowed: By line 6, with the fixed multiple 3.

  8. the move: a floor

    the line:
    M≥n24M \ge \frac{n^2}{4}

    why it is allowed: Rounding up never makes a number smaller, so line 5's ⌈n2⌉+1\lceil \frac{n}{2} \rceil + 1 is more than n2\frac{n}{2}. Rounding down takes off less than 1, so ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1 is more than n2\frac{n}{2} too. Multiply, as n2\frac{n}{2} times n2\frac{n}{2} is n24\frac{n^2}{4}; the last 1 only adds. For 6, 17 against 9.

  9. the move: read the bound

    the line:
    M∈Ω(n2)M \in \Omega(n^2)

    why it is allowed: By line 8, with the fixed multiple a quarter.

  10. the move: both together

    the line:
    M∈Θ(n2)M \in \Theta(n^2)

    why it is allowed: Lines 7 and 9 bound MM by the same growth.

try it with a small nn: at n=6n = 6, line 4 gives M=17M = 17, which you can work out by hand

Question 3: a pattern of mm letters on a text of nn costs at most (n−m+2)+m(n−m+1)(n - m + 2) + m(n - m + 1) steps. Which mm gives the most, and what is that most, PP?
  1. the move: a ceiling for one length

    the line:
    m letters cost at most(n−m+2)+m(n−m+1)\begin{gathered} m \text{ letters cost at most} \\ (n - m + 2) + m(n - m + 1) \end{gathered}
    mfingerprintscomparisonsat most
    17613
    261016
    351217
    441216
    531013
    6268
    A text of 6 letters, every pattern length, the comparisons at their most. The ceiling climbs to 17 at 3 letters, then falls.

    why it is allowed: The fingerprints are n−m+2n - m + 2, by question 1's line 2. At most mm comparisons at a place, by question 2's line 1, and n−m+1n - m + 1 places, by question 1's line 1. For 6 letters and 3, 5 + 12, which is 17.

  2. the move: gather the places

    the line:
    that is(m+1)(n−m+1)+1\begin{gathered} \text{that is} \\ (m + 1)(n - m + 1) + 1 \end{gathered}

    why it is allowed: Line 1's n−m+2n - m + 2 is the places, n−m+1n - m + 1, plus 1. The places taken mm times and once more make m+1m + 1 times, and the 1 stays. For 6 and 3, 4 times 4, plus 1, which is 17.

  3. the move: a fixed sum

    the line:
    the two parts add upto n+2\begin{gathered} \text{the two parts add up} \\ \text{to } n + 2 \end{gathered}

    why it is allowed: Line 2's parts, m+1m + 1 and n−m+1n - m + 1, add up to n+2n + 2, whatever mm is. For 6, 4 and 4 make 8, and so do 3 and 5.

  4. the move: even out the parts

    the line:
    (x−1)(y+1)is xy+(x−y−1)\begin{gathered} (x - 1)(y + 1) \\ \text{is } xy + (x - y - 1) \end{gathered}
    xysumproduct
    53815
    44816
    Move 1 from 5 to 3. The sum stays 8, and the product grows from 15 to 16.

    why it is allowed: Take two parts xx and yy, xx at least 2 more than yy. Move 1 from xx to yy; the sum stays the same, and multiplying out gives the line. x−y−1x - y - 1 is at least 1, so the product grows. For 5 and 3, 4 times 4 is 16, more than 15.

  5. the move: the most

    the line:
    most at parts ⌈n2⌉+1and ⌊n2⌋+1\begin{gathered} \text{most at parts } \lceil \frac{n}{2} \rceil + 1 \\ \text{and } \lfloor \frac{n}{2} \rfloor + 1 \end{gathered}

    why it is allowed: Moving 1 between the parts is a pattern 1 letter shorter or longer. By line 4, while the parts are 2 or more apart, moving 1 from the larger to the smaller makes the product grow. So the most is where they are at most 1 apart. By line 3 they add up to n+2n + 2, and the only whole parts that do so at most 1 apart are ⌈n2⌉+1\lceil \frac{n}{2} \rceil + 1 and ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1. As m+1m + 1 is the first part, mm is ⌈n2⌉\lceil \frac{n}{2} \rceil. From 3 on, an odd nn ties it with ⌊n2⌋\lfloor \frac{n}{2} \rfloor, the parts swapped; at 1, that would be 0 letters. For 7, 3 letters tie with 4.

  6. the move: the most of any length

    the line:
    P=(⌈n2⌉+1)(⌊n2⌋+1)+1P = (\lceil \frac{n}{2} \rceil + 1)(\lfloor \frac{n}{2} \rfloor + 1) + 1

    why it is allowed: By lines 2 and 5, multiply the two closest parts and add 1. That is PP, the most line 1's ceiling reaches, so a pattern of ⌈n2⌉\lceil \frac{n}{2} \rceil letters has the highest ceiling of any length. For 6, 17; for 7, 21.

  7. the move: no search costs more

    the line:
    M is the most ofany search of n letters\begin{gathered} M \text{ is the most of} \\ \text{any search of } n \text{ letters} \end{gathered}

    why it is allowed: By lines 1 and 6, no pattern on a text of nn letters costs more than PP. Question 2's line 5 shows MM equals PP, so its text and pattern cost the most. For 6, 17.

try it with a small nn: at n=6n = 6, line 6 gives P=17P = 17, which you can work out by hand

count it yourself

A text of 6 a's and the pattern aaa, question 2's worst at 6. Every fingerprint is 10, so every place agrees, and all 3 letters match at each. A position is a letter's number in the text, from 1.

aaaaaa, aaa, every step written down
stepthe rowwhat happensletters comparedfingerprints worked outfingerprints and comparisons
1Look for aaa in aaaaaa. Read letters as numbers, a as 1 up to z as 26, and give each piece of text a fingerprint to compare before its letters.000
2aaa read as a number in base 26 leaves 10 when divided by 11: that is the pattern's fingerprint.011
310The text under the pattern's first place, worked out the same way, has the fingerprint 10.10022
410The fingerprint here is 10, the same as the pattern's. Two pieces can share one, so compare the letters to be sure.10022
510The text's a at position 1 matches the pattern's a.10123
610The text's a at position 2 matches the pattern's a.10224
710The text's a at position 3 matches the pattern's a.10325
810Every letter agrees: the pattern stands at place 1. Mark it.10325
910, 10Move the pattern on to place 2. Take a off the front of the fingerprint and add a at the end, giving 10.10, 10336
1010, 10The fingerprint here is 10, the same as the pattern's. Two pieces can share one, so compare the letters to be sure.10, 10336
1110, 10The text's a at position 2 matches the pattern's a.10, 10437
1210, 10The text's a at position 3 matches the pattern's a.10, 10538
1310, 10The text's a at position 4 matches the pattern's a.10, 10639
1410, 10Every letter agrees: the pattern stands at place 2. Mark it.10, 10639
1510, 10, 10Move the pattern on to place 3. Take a off the front of the fingerprint and add a at the end, giving 10.10, 10, 106410
1610, 10, 10The fingerprint here is 10, the same as the pattern's. Two pieces can share one, so compare the letters to be sure.10, 10, 106410
1710, 10, 10The text's a at position 3 matches the pattern's a.10, 10, 107411
1810, 10, 10The text's a at position 4 matches the pattern's a.10, 10, 108412
1910, 10, 10The text's a at position 5 matches the pattern's a.10, 10, 109413
2010, 10, 10Every letter agrees: the pattern stands at place 3. Mark it.10, 10, 109413
2110, 10, 10, 10Move the pattern on to place 4. Take a off the front of the fingerprint and add a at the end, giving 10.10, 10, 10, 109514
2210, 10, 10, 10The fingerprint here is 10, the same as the pattern's. Two pieces can share one, so compare the letters to be sure.10, 10, 10, 109514
2310, 10, 10, 10The text's a at position 4 matches the pattern's a.10, 10, 10, 1010515
2410, 10, 10, 10The text's a at position 5 matches the pattern's a.10, 10, 10, 1011516
2510, 10, 10, 10The text's a at position 6 matches the pattern's a.10, 10, 10, 1012517
2610, 10, 10, 10Every letter agrees: the pattern stands at place 4. Mark it.10, 10, 10, 1012517
2710, 10, 10, 10Every place has been tried. The pattern stands at 4 places. That took 5 fingerprints and 12 comparisons.10, 10, 10, 1012517

In all, 17 fingerprints and comparisons. The formula from section 4, (⌈n2⌉+1)(⌊n2⌋+1)+1(\lceil \frac{n}{2} \rceil + 1)(\lfloor \frac{n}{2} \rfloor + 1) + 1, gives M=17M = 17 at n=6n = 6: the same.

where you meet it

The books slide a fingerprint along a courier's log. A paper on spotting copied work fingerprints every run of letters. Go, a programming language, switches to this method for a long pattern, when its usual search keeps failing.

  • The courier's afternoon

    The books turn a courier's 28 stops into digits 0 to 5 and search them for a run of 6. They roll the number along as section 1 does, three moves a stop: take off, multiply, add. Only stop 21 agrees, and checking it costs 6 comparisons. Dividing by a small number such as 13 makes chance agreements common: 83 wasted checks in every 1,000 characters.

    source: the books' volume four, chapter 41

  • Spotting copied work

    Schleimer, Wilkerson and Aiken's paper finds copied documents and code. It works out a fingerprint of every run of a fixed number of letters, each from the one before, as this page does. It keeps some of them to compare.

    source: S. Schleimer, D. S. Wilkerson and A. Aiken, SIGMOD 2003, pages 76 to 85, Winnowing: local algorithms for document fingerprinting (opens in a new tab)

  • Go's strings.Index

    For a long pattern, Go's strings.Index looks for the first two letters and compares the rest. When that keeps failing, it switches to Rabin-Karp: a rolling fingerprint, and the letters checked only where it agrees.

    source: Go's source, Index in src/internal/stringslite/strings.go (opens in a new tab), which strings.Index calls, and IndexRabinKarp in src/internal/bytealg/bytealg.go

what is used instead

For one pattern, Knuth-Morris-Pratt promises never to compare more than twice the text's length plus the pattern's, as its own page shows. On ordinary text the books reach for Boyer-Moore, which jumps ahead; Horspool is its simpler form. The books reach for Rabin-Karp when there are many patterns at once.

how it compares

The four searches on the watch page's first example, and on 10 a's and bbbbb. Rabin-Karp compares few letters while its fingerprints rarely agree, but works one out at every place.

methodcomparisonsalso
brute force8
Horspool5
Knuth-Morris-Pratt10its table's 2 included
Rabin-Karp47 fingerprints
kangaroo and roo, each method's own count. Only places 3 and 6 share roo's fingerprint, so Rabin-Karp compares letters there alone.
methodcomparisonsalso
brute force6
Horspool2
Knuth-Morris-Pratt10its table's 4 included
Rabin-Karp67 fingerprints
10 a's and bbbbb. Every place agrees by chance, so Rabin-Karp compares as brute force does, and works out 7 fingerprints besides.

race them on one row of your own