Skip to content

Brute-force search

words

Level 1 of 3

Also called Naive string search.

how it works

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

Look for bag in cabbage. Put bag under the text's first letter and compare from the left. c is not b, so move bag on one place. a is not b: move on. At place 3, b matches b, then b is not a: move on. At place 4, b, a and g all match, so bag stands at place 4. Its b is the text's letter 4, which place 3 read already: brute force reads some letters more than once. At place 5, a is not b. Every place is tried. That is the whole method. Try every place, compare from the left until a letter differs, then move on one. 7 letters and 3 give 7 - 3 + 1, which is 5 places. They cost 1 + 1 + 2 + 3 + 1, which is 8 comparisons. The code below counts places from 0 and returns them in a list, so it returns [3].

placeletters abovematchedcomparisons
1cab01
2abb01
3bba12
4bag3, a match3
5age01
all8
bag under each place of cabbage. A place costs the letters that matched, plus 1 for the letter that differed. At place 4 all 3 match, so 3.
Bag in cabbage: 6 moments of its 19 steps, the steps between them left for the watch page
  1. step 1 of 19

    cabbagebag12345

    Look for bag in cabbage. The pattern can stand at 5 places, so try each in turn, starting under the first letter.

    what it remembers to know where it is
    pattern stands at place
    1
    letters matched here
    not yet

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

    watch from here

  2. step 3 of 19

    cabbagebag123450

    No letter matched at place 1. Write it in the table.

    what it remembers to know where it is
    pattern stands at place
    1
    letters matched here
    0

    watch from here

  3. step 9 of 19

    cabbagebag1234500

    The text's b at position 4 is not the pattern's a, so the pattern does not stand here.

    what it remembers to know where it is
    pattern stands at place
    3
    letters matched here
    1

    watch from here

  4. step 10 of 19

    cabbagebag12345001

    1 letter matched at place 3. Write it in the table.

    what it remembers to know where it is
    pattern stands at place
    3
    letters matched here
    1

    watch from here

  5. step 15 of 19

    cabbagebag123450013

    Every letter matched: the pattern stands at place 4. Mark it and write it in the table.

    what it remembers to know where it is
    pattern stands at place
    4
    letters matched here
    3

    watch from here

  6. step 19 of 19

    cabbagebag1234500130

    Every place has been tried. The pattern stands at 1 place. That took 8 comparisons.

    what it remembers to know where it is
    pattern stands at place
    5
    letters matched here
    0

    watch from here

the steps, in plain words
  1. for each place the pattern can stand, from the start of the textPython line 9
  2. compare its letters with the text's, from the left, until one differsPython lines 11, 12 and 13
  3. write how many matched; if all of them did, mark a matchPython lines 14 and 15
  4. move the pattern on one placePython line 9
  5. every place tried, so every match is foundPython line 16
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 brute_force_search(text, pattern):
    """Find every place a pattern stands in a text, by trying them all.

    text and pattern are each a run of letters, the pattern no longer than
    the text. Returns the places it stands, counted from 0.
    """
    n, m = len(text), len(pattern)
    places = []
    for place in range(n - m + 1):  # each place the pattern can stand, from the start
        matched = 0
        # compare its letters with the text's, from the left, until one differs
        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 the comparisons on a text of nn letters and a pattern half as long, rounded up, in two ways. The best never matches a first letter. The worst matches every letter but the last, at every place. 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: 51 comparisons at 100 letters, 501 at 1,000. The worst climbs two marks up for each mark across: 2,550 at 100, 250,500 at 1,000. Ten times the letters, about 100 times the comparisons. Section 4 derives both.

letters compared, 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 ending in b, 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 b's, 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 comparisons a second
nnletters comparedtime
1,000250,500about 251 microseconds
100,0002,500,050,000about 2.5 seconds
10,000,00025,000,005,000,000about 6.9 hours

The letters compared 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 brute-force search's comparisons 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:
all b, so the first letter differs at every place, the fewest; and a's
ending in one b, so every letter is compared at every place, the most. It
prints the comparisons for each, by count below, which counts 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 brute_force_search(text, pattern):
    """Find every place a pattern stands in a text, by trying them all.

    text and pattern are each a run of letters, the pattern no longer than
    the text. Returns the places it stands, counted from 0.
    """
    n, m = len(text), len(pattern)
    places = []
    for place in range(n - m + 1):  # each place the pattern can stand, from the start
        matched = 0
        # compare its letters with the text's, from the left, until one differs
        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 comparisons brute_force_search makes: one for each letter
    of the text it compares with a letter of the pattern."""
    n, m = len(text), len(pattern)
    compared = 0
    for place in range(n - m + 1):
        matched = 0
        while matched < m:
            compared += 1
            if text[place + matched] != pattern[matched]:
                break
            matched += 1
    return compared


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


def dearest(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"


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

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 can cost the most. Both have the same places, ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1, by section 4's question 1; only the letters differ. For 6 letters and 3: 4 places, 4 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 500 times 501: 500 times 500, which is 250,000, plus 500. They are the pieces 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 b's, half as longworsta text of a's and a pattern of a's ending in b, half as long
letters compared⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1⌈n2⌉(⌊n2⌋+1)\lceil \frac{n}{2} \rceil (\lfloor \frac{n}{2} \rfloor + 1)
how the letters compared 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 numbers, 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.

textpatternplacescomparisons
cabbagebag58
bananaana48
breakfastquick55
aaaaaaaaaaaaaab630
The watch page's four examples. breakfast has no q, so each place costs 1. The 10 a's cost 5 at every place.
nbestworst
6412
7416
10630
The two cases, a pattern half the text, rounded up. At 10 letters the worst is the watch page's last example.

where the formula comes from

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

Question 1: how many comparisons, FF, on a text of nn a's and a pattern of b's 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}
    placeunder letters
    11 to 3
    22 to 4
    33 to 5
    44 to 6
    A pattern of 3 under a text of 6. At place 4 its last letter is under letter 6, so there is no place 5.

    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, and its mm letters cover letters n−m+1n - m + 1 to nn. For 6 letters and 3, places 1 to 4.

  2. 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.

  3. the move: one comparison a place

    the line:
    F=n−⌈n2⌉+1F = n - \lceil \frac{n}{2} \rceil + 1
    placeletters aboveagainstcomparisons
    1aaabbb1
    2aaabbb1
    3aaabbb1
    4aaabbb1
    all4
    A text of 6 a's and the pattern bbb. At each of the 4 places, a is not b at once. 4 places, 4 comparisons.

    why it is allowed: The text is all a and the pattern all b. At each place the first comparison differs, and the pattern moves on. So one comparison at each place of line 1, with line 2's mm. For 6, 4.

  4. the move: half, rounded down

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

    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.

  5. the move: a ceiling

    the line:
    F≤nF \le n

    why it is allowed: From 1 up, half of nn rounded down is a whole number below nn, so at most the whole number just below nn. Adding 1 gives at most nn. For 1, 0 + 1 is 1, exactly nn; for 6, 4.

  6. the move: read the bound

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

    why it is allowed: By line 5, with the fixed multiple 1.

  7. 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 4's ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1 is more than n2\frac{n}{2}. For 7, 4 against 3.5.

  8. the move: read the bound

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

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

  9. the move: both together

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

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

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

Question 2: how many comparisons, MM, on a text of nn a's and a pattern of a's ending in b, 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: At a place the pattern's letters are compared from the left, one each, until one differs. It has mm letters, so at most mm.

  2. the move: every letter but the last matches

    the line:
    a’s ending in b:m at every place\begin{gathered} \text{a's ending in b:} \\ m \text{ at every place} \end{gathered}
    placeletters aboveagainstcomparisons
    1aaaaab3
    2aaaaab3
    3aaaaab3
    4aaaaab3
    all12
    A text of 6 a's and the pattern aab. At each of the 4 places, a and a match, then b differs. 4 times 3 is 12.

    why it is allowed: The text is all a, and so is every letter of the pattern but the last. Those match at every place, and the last, b, differs. So all mm letters are compared at every place.

  3. the move: multiply by the places

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

    why it is allowed: By line 2, mm comparisons at each place, with mm as ⌈n2⌉\lceil \frac{n}{2} \rceil by section 4's question 1, line 2. Question 1 made one comparison at each place, ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1 in all, by its lines 3 and 4, so there are ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1 places. Multiply the two. For 6, 3 times 4, which is 12; for 7, 4 times 4, which is 16.

  4. the move: a ceiling

    the line:
    M≤n2M \le n^2

    why it is allowed: Half of nn is at most nn, a whole number, so rounding it up stays at most nn. ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1 is at most nn by section 4's question 1, line 5. Multiply the two. For 6, 12 is at most 36.

  5. the move: read the bound

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

    why it is allowed: By line 4, with the fixed multiple 1.

  6. 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 ⌈n2⌉\lceil \frac{n}{2} \rceil is at least n2\frac{n}{2}. By section 4's question 1, line 7, ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1 is more than n2\frac{n}{2}. Multiply the two, as n2\frac{n}{2} times n2\frac{n}{2} is n24\frac{n^2}{4}. For 6, 12 against 9.

  7. the move: read the bound

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

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

  8. the move: both together

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

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

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

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

    the line:
    m letters costat most m(n−m+1)\begin{gathered} m \text{ letters cost} \\ \text{at most } m(n - m + 1) \end{gathered}
    mplacesat most
    166
    2510
    3412
    4312
    5210
    616
    A text of 6 letters, every pattern length. The ceiling climbs to 12 at 3 and 4 letters, then falls.

    why it is allowed: 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. Multiply the two. For 6 letters and 3, 3 times 4, which is 12.

  2. the move: a fixed sum

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

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

  3. 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}

    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 2, 4 times 3 is 12, more than 10.

  4. the move: the most

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

    why it is allowed: By line 3, while the parts are 2 or more apart, their product can still grow. By line 2 they add up to n+1n + 1. ⌈n2⌉\lceil \frac{n}{2} \rceil and ⌊n2⌋+1\lfloor \frac{n}{2} \rfloor + 1 add up to n+1n + 1 too, by question 1's line 4, and they are at most 1 apart, so they are the closest, either way round. For 6, 3 and 4, 12; for 7, 4 and 4, 16.

  5. the move: the most of any length

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

    why it is allowed: By line 4, multiply the two closest parts. 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 an even nn, one letter more ties it, as 4 letters do for 6.

  6. 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 5, no pattern on a text of nn letters costs more than PP. Question 2's line 3 is the same product, so its text and pattern meet it, and MM is the most. For 6, 12.

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

count it yourself

A text of 6 a's and the pattern aab, question 2's worst at 6. At each place a and a match, then b differs. A position is a letter's number in the text, from 1. The second column lists how many letters matched at each place so far; the last column is a running total.

aaaaaa, aab, every step written down
stepthe rowwhat happensletters compared
1Look for aab in aaaaaa. The pattern can stand at 4 places, so try each in turn, starting under the first letter.0
2The text's a at position 1 matches the pattern's a.1
3The text's a at position 2 matches the pattern's a.2
4The text's a at position 3 is not the pattern's b, so the pattern does not stand here.3
522 letters matched at place 1. Write it in the table.23
62Move the pattern on one place, to place 2, and start again from its first letter.23
72The text's a at position 2 matches the pattern's a.24
82The text's a at position 3 matches the pattern's a.25
92The text's a at position 4 is not the pattern's b, so the pattern does not stand here.26
102, 22 letters matched at place 2. Write it in the table.2, 26
112, 2Move the pattern on one place, to place 3, and start again from its first letter.2, 26
122, 2The text's a at position 3 matches the pattern's a.2, 27
132, 2The text's a at position 4 matches the pattern's a.2, 28
142, 2The text's a at position 5 is not the pattern's b, so the pattern does not stand here.2, 29
152, 2, 22 letters matched at place 3. Write it in the table.2, 2, 29
162, 2, 2Move the pattern on one place, to place 4, and start again from its first letter.2, 2, 29
172, 2, 2The text's a at position 4 matches the pattern's a.2, 2, 210
182, 2, 2The text's a at position 5 matches the pattern's a.2, 2, 211
192, 2, 2The text's a at position 6 is not the pattern's b, so the pattern does not stand here.2, 2, 212
202, 2, 2, 22 letters matched at place 4. Write it in the table.2, 2, 2, 212
212, 2, 2, 2Every place has been tried. The pattern stands nowhere in the text. That took 12 comparisons.2, 2, 2, 212

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

where you meet it

The books' dispatcher searches a courier's log this way. So does Java's plain search. A paper on a faster search opens with this method's worst case.

  • The dispatcher's log

    The books give a dispatcher a courier's afternoon, 28 stops, one letter each, to search for a run of 6. This method makes 58 comparisons, and 32 of them read a letter it has read before.

    source: the books' volume four, chapter 41

  • Java's indexOf

    Java is a programming language, and OpenJDK is its free reference version. Its String.indexOf, in plain Java, finds the pattern's first letter in the text, then compares the rest. When a letter differs, it moves on one place, as this page does.

    source: OpenJDK's indexOf and indexOf0, in the java.base module, java/lang/StringLatin1.java (opens in a new tab)

  • A faster search

    Knuth, Morris and Pratt's 1977 paper gives this method's worst case as its first example, a pattern of a's ending in b. It gives a method that never steps back in the text, its comparisons growing with the two lengths added.

    source: D. E. Knuth, J. H. Morris and V. R. Pratt, SIAM Journal on Computing 6(2), 1977, pages 323 to 350, Fast pattern matching in strings (opens in a new tab)

what is used instead

On a long or repetitive text, study the pattern first. Knuth-Morris-Pratt never steps back in the text. Horspool jumps ahead by a table of letters. Rabin-Karp compares fingerprints first. The books cover the first and the third.

how it compares

Three rivals study the pattern before they look at the text. On the watch page's dearest example, each makes fewer comparisons, Horspool and Rabin-Karp far fewer.

methodstudies firstworst comparisons
brute forcenothingm(n−m+1)m(n - m + 1), at most mnmn
Horspoola jump for each letterthe same
Knuth-Morris-Prattthe pattern against itselfat most twice the two lengths added
Rabin-Karpthe pattern's fingerprintthe same
The four searches on the watch pages, for a pattern of mm letters; m(n−m+1)m(n - m + 1) is at most mnmn, as n−m+1n - m + 1 is at most nn. Brute force, Horspool and Rabin-Karp all reach m(n−m+1)m(n - m + 1) on a text of a's and a pattern of a's, such as aaa in aaaaaa.
methodcomparisonsalso
brute force30
Horspool6
Knuth-Morris-Pratt22its table included
Rabin-Karp07 fingerprints
10 a's and aaaab, each method's own count. Rabin-Karp's fingerprints never agree, so it compares no letter.

race them on one row of your own