The Boyer-Moore Algorithm

Fractional CTO · Founder of Injuria.ai
The Boyer-Moore string-search algorithm is a highly efficient text-matching algorithm that functions as the standard benchmark for practical string search literature. Developed by Robert S. Boyer and J Strother Moore in 1977, the algorithm determines the exact occurrence of a specific pattern within a larger body of text. Unlike naive search methods that examine every character of the text sequentially from left to right, Boyer-Moore compares the pattern against the text from right to left. This counterintuitive approach allows the algorithm to skip multiple characters at once when a mismatch occurs, bypassing large sections of the text entirely.
By utilizing two precomputed tables based on the pattern being searched, the algorithm calculates the maximum safe shift distance after any mismatch. The longer the pattern, the faster the algorithm generally performs, as longer patterns enable larger shifts. This property makes the algorithm exceptionally well suited for natural language processing, text editors, and database queries where the search pattern consists of several characters and the alphabet is relatively large.
Since its publication, the algorithm has profoundly influenced computer science, spawning dozens of variants and optimizations. It forms the foundation of many standard library search functions and command-line utilities, including the widely used GNU grep. Its theoretical properties, particularly its sublinear average-case time complexity, have been the subject of extensive mathematical analysis, establishing it as a foundational concept in the study of string matching and computational complexity.
Definition and Problem Statement
The exact string matching problem is a fundamental challenge in computer science.[22] Given a text string $T$ of length $n$ and a pattern string $P$ of length $m$, the objective is to find all valid shifts or starting positions $s$ (where $0 \le s \le n - m$) such that the pattern appears exactly within the text. This requires that $T[s + j] == P[j]$ for all $0 \le j < m$. Both strings are constructed from a finite set of characters known as the alphabet, denoted by $\Sigma$.
A naive or brute-force approach to this problem aligns the pattern with the beginning of the text and compares characters one by one from left to right. If a mismatch occurs, the pattern is shifted one position to the right, and the comparison begins again from the first character of the pattern. In the worst case, this method requires $O(n \cdot m)$ comparisons. For a text of several megabytes and a pattern of a few dozen characters, this multiplicative overhead becomes highly inefficient.
The Boyer-Moore algorithm solves this problem by preprocessing the pattern to gather structural information before the search begins. This preprocessing step generates two heuristic tables that dictate how far the pattern can be shifted along the text when a mismatch is detected. During the search phase, the algorithm aligns the pattern with the text but performs the character comparisons from right to left, starting with the last character of the pattern (index $m - 1$).
When a mismatch is found, the algorithm consults the two precomputed tables, determines the recommended shift distance from each, and applies the larger of the two shifts. This mechanism ensures that the algorithm never misses a valid match while maximizing the number of text characters skipped. Because the algorithm can skip over characters without examining them, it often achieves sublinear performance in practice. In optimal scenarios, the algorithm examines only a fraction of the characters in the text, leading to an average-case time complexity of $O(n / m)$.[23] This efficiency addresses the primary bottleneck of string searching in large datasets, reducing the computational overhead required for text retrieval, data filtering, and pattern recognition.
Discovery and Historical Context
The algorithm was developed by Robert S. Boyer and J Strother Moore while they were researchers at SRI International (formerly the Stanford Research Institute). They formalized the method around 1974 and published their findings in the October 1977 issue of the Communications of the ACM under the title "A Fast String Searching Algorithm" A Fast String Searching Algorithm (Boyer and Moore, 1977)[1].[24]
At the time of its development, string searching was generally performed using hardware-specific instructions or naive loops that processed every character sequentially. Boyer and Moore implemented their original algorithm in assembly language for the PDP-10 mainframe computer. The PDP-10 instruction set lacked a dedicated instruction for incrementing a byte pointer by arbitrary amounts, forcing the authors to use an array of 128 indexing byte pointers to access characters efficiently. Despite this hardware limitation, they successfully reduced the fast search loop to just four machine instructions, proving the extreme practical efficiency of their right-to-left scanning approach.
The invention of the algorithm occurred during a period of rapid advancement in pattern matching. In the same year, Donald Knuth, James H. Morris, and Vaughan Pratt published the Knuth-Morris-Pratt algorithm Fast pattern matching in strings (Knuth, Morris, Pratt, 1977)[2], which also preprocessed the pattern to achieve a linear worst-case time complexity of $O(n + m)$. However, while Knuth-Morris-Pratt scanned the text from left to right and examined every character at least once, Boyer and Moore introduced the concept of right-to-left scanning combined with character skipping.
The original paper by Boyer and Moore presented the two primary shift heuristics and provided empirical evidence of the algorithm's sublinear average-case behavior. However, the theoretical analysis of its worst-case performance proved difficult.[25] Boyer and Moore conjectured that the worst-case number of comparisons was linear, but they did not provide a complete mathematical proof in their initial publication.
In 1977, Leonidas Guibas and Andrew Odlyzko published a rigorous mathematical proof demonstrating that the worst-case behavior of the original Boyer-Moore algorithm was indeed linear, bounded by $4n$ comparisons [3]. This bound was the subject of intense mathematical scrutiny for over a decade. In 1994, Richard Cole published a definitive analysis proving an upper bound of roughly $3n$ comparisons (specifically $3n - 3(n - m + 1) / (m + 2)$), establishing a tight upper bound for the algorithm's worst-case performance Tight bounds on the complexity of the Boyer-Moore pattern matching algorithm (Cole, 1994).
The preprocessing phase of the algorithm also underwent historical refinement. The original paper described a method for constructing the shift tables, but it contained subtle flaws that could lead to incorrect shift values under specific conditions. In 1980, Wojciech Rytter published a corrected and efficient algorithm for generating the shift tables, ensuring that the preprocessing phase could be completed in $O(m)$ time and space A Correct Preprocessing Algorithm for Boyer-Moore String-Searching (Rytter, 1980)[4].
Algorithmic Mechanism
The Boyer-Moore algorithm operates in two distinct phases: the preprocessing phase and the searching phase. During preprocessing, the algorithm analyzes the pattern to construct two tables, known as the bad character table and the good suffix table. During the searching phase, the algorithm uses these tables to slide the pattern along the text.
The search aligns the pattern with the text and compares characters starting from the rightmost position of the pattern (index $m - 1$). If the characters match, the algorithm moves one position to the left and compares the next pair of characters. This right-to-left scanning continues until either the entire pattern matches the text, or a mismatch occurs. When a mismatch occurs, the algorithm calculates a shift distance using both the bad character rule and the good suffix rule. It selects the maximum of these two values and shifts the pattern to the right by that amount.
The Bad Character Rule
The bad character rule is based on the text character that caused the mismatch. Suppose the algorithm is comparing the pattern to the text, and a mismatch occurs at pattern index $i$. Let the mismatched character in the text be $c$. The algorithm looks up the character $c$ in the precomputed bad character table.
The table records the rightmost occurrence of every character in the alphabet within the pattern. If the character $c$ exists in the pattern to the left of index $i$, the algorithm shifts the pattern so that the rightmost occurrence of $c$ in the pattern aligns with the character $c$ in the text. If $c$ does not exist in the pattern at all, the algorithm can safely shift the pattern entirely past the character $c$, resulting in a shift of $i + 1$ positions.
Consider a search for the pattern "EXAMPLE" within the text "HERE IS A SIMPLE EXAMPLE". The algorithm aligns "EXAMPLE" with "HERE IS". The rightmost character of the pattern is 'E', and it aligns with the text character 'S'. These do not match. The character 'S' is the "bad character". The algorithm checks the pattern "EXAMPLE" for the character 'S'. Since 'S' does not appear in the pattern, the algorithm determines that no part of the pattern can match the 'S'. It shifts the entire pattern past the 'S', moving it 7 positions to the right.
If the rightmost occurrence of $c$ in the pattern is to the right of index $i$, aligning them would require shifting the pattern to the left, which is invalid because the search must progress forward. In this scenario, the bad character rule proposes a shift of one position to the right, relying on the good suffix rule to provide a larger, more efficient shift.
The bad character table is constructed by allocating an array of size equal to the alphabet $\Sigma$. Initially, every entry in this array is set to a default value, typically $-1$. The algorithm then iterates through the pattern from left to right (index $0$ to $m - 1$). For each character encountered at index $j$, the array entry corresponding to that character is updated to $j$. This left-to-right iteration ensures that if a character appears multiple times in the pattern, the table records its rightmost occurrence.
The Good Suffix Rule
The good suffix rule utilizes the portion of the pattern that has already matched the text successfully. Suppose a mismatch occurs at pattern index $i$, meaning the substring from index $i + 1$ to $m - 1$ has matched the text. This matched substring is called the "good suffix", denoted as $t$.
The good suffix table provides the shift distance required to align the next occurrence of $t$ within the pattern with the matching text. The algorithm searches the pattern for the rightmost occurrence of $t$ that is preceded by a character different from the character at index $i$. If such an occurrence exists, the pattern is shifted to align it with the text.
If the exact suffix $t$ does not appear anywhere else in the pattern, the algorithm looks for the longest prefix of the pattern that matches a suffix of $t$. The pattern is then shifted to align this prefix with the corresponding suffix in the text. If neither condition is met, the pattern is shifted by its entire length, $m$.
Consider a search for the pattern "CABABA" in a text. Suppose the algorithm matches the suffix "ABA" but finds a mismatch on the character before it. The good suffix is "ABA". The algorithm looks for another instance of "ABA" in the pattern "CABABA". It finds one at the beginning of the pattern. It shifts the pattern to align this earlier "ABA" with the text that has already been matched. This prevents the algorithm from re-evaluating text characters that are already known to match the suffix.
The construction of the good suffix table relies on the concept of string borders. A border of a string is defined as a substring that is both a proper prefix and a proper suffix of that string. To populate the good suffix table, the preprocessing algorithm computes the border array of the pattern and the border array of the reversed pattern. This allows the algorithm to identify the longest matching prefixes and suffixes in $O(m)$ time.
Pseudocode
The following pseudocode illustrates the core searching phase of the algorithm, assuming the bad_char and good_suffix tables have already been populated during the preprocessing phase.
function BoyerMooreSearch(text, pattern):
n = length(text)
m = length(pattern)
if m == 0: return []
bad_char = BuildBadCharTable(pattern)
good_suffix = BuildGoodSuffixTable(pattern)
matches = []
shift = 0
while shift <= (n - m):
j = m - 1
while j >= 0 and pattern[j] == text[shift + j]:
j = j - 1
if j < 0:
matches.append(shift)
shift = shift + good_suffix[0]
else:
char_text = text[shift + j]
bc_shift = j - bad_char.get(char_text, -1)
gs_shift = good_suffix[j + 1]
shift = shift + max(bc_shift, gs_shift)
return matches
Complexity Analysis
The efficiency of the Boyer-Moore algorithm is highly dependent on the nature of the text and the pattern. The analysis is divided into the preprocessing phase and the searching phase.
The preprocessing phase requires iterating over the pattern to construct the bad character and good suffix tables. The bad character table requires space proportional to the size of the alphabet, $O(|\Sigma|)$, and time proportional to $O(m + |\Sigma|)$ to initialize. The good suffix table requires $O(m)$ time and space to construct. Therefore, the total time and space complexity for preprocessing is $O(m + |\Sigma|)$ Exact String Matching Algorithms: Boyer-Moore algorithm (Charras and Lecroq).
In the best-case scenario during the searching phase, the algorithm encounters a mismatch on the first character compared (the rightmost character of the pattern), and the mismatched text character does not appear anywhere in the pattern. The bad character rule will dictate a shift of $m$ positions. If this occurs repeatedly, the algorithm performs only $n / m$ comparisons, resulting in a best-case time complexity of $O(n / m)$. This sublinear behavior is the primary advantage of the algorithm.
The worst-case time complexity of the original algorithm is $O(n \cdot m)$ if the algorithm is used to find all occurrences of a pattern and no modifications are applied. For example, searching for the pattern "AAAAA" in a text of "AAAAAAAAAA" forces the algorithm to verify every match and shift by only one position. However, for finding a single match, the worst-case time complexity is linear, bounded by $O(n)$ as proven by Cole.
Space complexity is $O(m + |\Sigma|)$. For small alphabets like ASCII, the $O(|\Sigma|)$ space requirement is negligible (256 bytes). However, for modern Unicode text, allocating an array for all possible code points is highly inefficient. Implementations typically resolve this by using hash tables for the bad character rule or by falling back to simpler algorithms for large alphabets.
Important Variants and Refinements
The foundational concepts of the Boyer-Moore algorithm inspired numerous adaptations designed to improve its worst-case performance, simplify its implementation, or optimize it for specific hardware architectures.
The Galil Rule (1979)
In 1979, Zvi Galil introduced a modification to guarantee a linear worst-case time complexity of $O(n)$ even when searching for all occurrences of a pattern [5].[23] The Galil rule observes that if a pattern has a periodic structure, the algorithm does not need to re-verify the matching prefix after a shift. By recording the length of the matched prefix and skipping those comparisons in subsequent alignments, the Galil rule eliminates redundant character checks, ensuring strict linear time bounds without increasing the space complexity. Galil later expanded on these concepts to establish criteria for real-time string matching String matching in real time (Galil, 1981)[6].
Boyer-Moore-Horspool (1980)
R. Nigel Horspool published a simplified variant in 1980, noting that the good suffix rule is complex to implement and rarely utilized when searching natural language text Practical fast searching in strings (Horspool, 1980)[7]. The Horspool algorithm completely discards the good suffix table. Instead, it relies solely on a modified bad character rule, always using the text character aligned with the rightmost position of the pattern to determine the shift distance, regardless of where the mismatch occurs. This variant requires only $O(|\Sigma|)$ space and performs exceptionally well in practice, often outperforming the original algorithm on typical text due to its tighter inner loop Exact String Matching Algorithms: Horspool algorithm (Charras and Lecroq).
Apostolico-Giancarlo (1986)
Alberto Apostolico and Raffaele Giancarlo developed a variant in 1986 that further optimizes the worst-case behavior [8]. The Apostolico-Giancarlo algorithm maintains the right-to-left scanning but adds an auxiliary table to remember the lengths of suffixes matched in previous alignments. When the algorithm shifts the pattern, it uses this memory to skip over text characters that are already known to match. Apostolico and Giancarlo originally proved a $2n$ bound, which was later tightened to $1.5n$ by Crochemore and Lecroq, at the cost of additional space proportional to the text length.
Zhu-Takaoka (1987)
Rui Feng Zhu and Tadao Takaoka introduced a variant in 1987 that modifies the bad character heuristic to examine two consecutive text characters instead of one. By computing a two-dimensional bad character table, the algorithm determines shifts based on character pairs. This approach requires $O(|\Sigma|^2)$ space for the preprocessing table, which limits its use to small alphabets. However, for alphabets of moderate size, the Zhu-Takaoka variant produces significantly larger shifts than the original bad character rule, reducing the total number of comparisons.
Boyer-Moore-Sunday (1990)
Daniel M. Sunday introduced the Quick Search algorithm in 1990, which modifies the bad character heuristic A very fast substring search algorithm (Sunday, 1990)[9]. When a mismatch occurs, the Sunday variant examines the text character located immediately after the current alignment of the pattern. By calculating the shift based on this next character rather than the mismatched character, the algorithm often achieves larger shifts. This variant is particularly effective for short patterns and requires minimal preprocessing Exact String Matching Algorithms: Quick Search algorithm (Charras and Lecroq). Further tuning of the inner comparison loops has been extensively documented in software engineering literature Fast String Searching (Hume and Sunday, 1991)[10].
Colussi (1991)
Livio Colussi developed an algorithm that combines the optimal worst-case behavior of Knuth-Morris-Pratt with the practical skipping efficiency of Boyer-Moore Correctness and efficiency of the pattern matching algorithms (Colussi, 1991). The Colussi algorithm partitions the positions of the pattern into two disjoint subsets, termed "holes" and "no-holes". During a search alignment, the algorithm first compares the no-holes from left to right. If all no-holes match, it compares the holes from right to left. This strict ordering guarantees that the algorithm performs at most $1.5n$ character comparisons in the worst case, without requiring the dynamic memory overhead of the Apostolico-Giancarlo variant.
Turbo Boyer-Moore (1992)
Maxime Crochemore and colleagues introduced the Turbo Boyer-Moore algorithm in 1992 Exact String Matching Algorithms: Turbo-BM algorithm (Charras and Lecroq). This variant retains the $O(1)$ extra space property of the original algorithm (excluding the precomputed tables) but introduces a "turbo shift" mechanism. It remembers the length of the good suffix matched in the previous alignment. If the current matched suffix is shorter than the previous one, the algorithm can safely jump over the previously matched characters, ensuring a tight $2n$ upper bound on comparisons.
Real-World Applications
The practical efficiency of the Boyer-Moore algorithm and its variants has led to their integration into numerous software systems, programming languages, and networking tools. Experimental results consistently show that Boyer-Moore variants dominate practical string matching tasks on standard text Fast exact string matching algorithms (Lecroq, 2007)[11].
One of the most famous implementations is in the GNU grep utility. Mike Haertel, the original author of GNU grep, utilized the Boyer-Moore algorithm to achieve extraordinary search speeds. In a 2010 mailing list post, Haertel explained that the utility's performance stems from avoiding the inspection of every input byte and executing very few instructions per byte examined why GNU grep is fast (Haertel, 2010)[12]. By reading raw data into large buffers and applying the Boyer-Moore shift heuristics, GNU grep routinely outperforms other search utilities.
In modern programming languages, the algorithm is frequently provided in standard libraries. The C++17 standard introduced std::boyer_moore_searcher, which allows developers to use the algorithm seamlessly with the std::search function std::boyer_moore_searcher (cppreference)[13]. This implementation handles the preprocessing of the pattern and provides an optimized search execution for iterators, requiring random access iterators to function correctly.
The Python programming language utilizes a hybrid approach for its str.find() and str.index() methods. The underlying C implementation, found in fastsearch.h, employs a combination of the Boyer-Moore-Horspool bad character rule and elements of the Sunday algorithm CPython fastsearch.h source code[14]. To handle the massive Unicode alphabet without allocating a full $O(|\Sigma|)$ array, Python's implementation uses a Bloom filter to quickly check if a character exists in the pattern, maintaining sublinear performance while keeping memory overhead strictly bounded.
In the field of cybersecurity, network intrusion detection systems like Snort rely heavily on fast string matching to scan packet payloads for malicious signatures. While multi-pattern algorithms like Aho-Corasick Efficient string matching: An aid to bibliographic search (Aho and Corasick, 1975)[15] are often used for simultaneous searches, single-pattern matching engines frequently employ Boyer-Moore variants to quickly discard benign traffic.
Significance and Tradeoffs
The Boyer-Moore algorithm fundamentally altered the theoretical and practical approaches to string searching. Prior to its publication, algorithms were generally expected to examine every character of the input text. By demonstrating that information gained from a mismatch could be used to skip characters, Boyer and Moore established a new paradigm in algorithmic design. The algorithm remains a standard baseline against which new string matching techniques are evaluated [16]. Recent advancements in text sampling continue to build upon the skipping principles established by Boyer and Moore [17].
Despite its widespread use, the algorithm is not universally optimal and involves specific tradeoffs. Its performance is highly dependent on the size of the alphabet. In texts with large alphabets, such as English prose or source code, mismatches frequently involve characters that do not appear in the pattern, triggering maximum shifts. However, in texts with very small alphabets, such as binary data or DNA sequences (which contain only four characters), the bad character rule becomes largely ineffective. In these cases, the algorithm frequently shifts by only one or two positions, and the overhead of right-to-left scanning can make it slower than simpler methods.
The preprocessing overhead also limits the algorithm's utility for very short patterns or very short texts. If the pattern is only two or three characters long, the time spent building the shift tables may exceed the time saved during the search. For extremely short patterns, naive searching or hardware-accelerated vector instructions are generally preferred. Bit-parallel algorithms like Shift-Or A new approach to text searching (Baeza-Yates and Gonnet, 1992)[18] often provide better performance for very short patterns. Modern bit-parallel suffix automata also compete in this space [19].
Furthermore, the original algorithm is designed for single-pattern searching. When an application requires searching for hundreds or thousands of patterns simultaneously, algorithms designed for multiple string matching, such as the Factor Oracle Factor oracle: A new structure for pattern matching (Allauzen et al., 1999)[20] or FM-index Indexing compressed text (Ferragina and Manzini, 2005)[21], are more appropriate. Nevertheless, for single-pattern searches in standard text, the Boyer-Moore algorithm and its descendants remain among the most efficient solutions available in computer science.
Sources (25)
- A Fast String Searching Algorithm (Boyer and Moore, 1977)
- Fast pattern matching in strings (Knuth, Morris, Pratt, 1977)
- doi.org
- A Correct Preprocessing Algorithm for Boyer-Moore String-Searching (Rytter, 1980)
- doi.org
- String matching in real time (Galil, 1981)
- Practical fast searching in strings (Horspool, 1980)
- doi.org
- A very fast substring search algorithm (Sunday, 1990)
- Fast String Searching (Hume and Sunday, 1991)
- Fast exact string matching algorithms (Lecroq, 2007)
- why GNU grep is fast (Haertel, 2010)
- std::boyer_moore_searcher (cppreference)
- CPython fastsearch.h source code
- Efficient string matching: An aid to bibliographic search (Aho and Corasick, 1975)
- doi.org
- doi.org
- A new approach to text searching (Baeza-Yates and Gonnet, 1992)
- doi.org
- Factor oracle: A new structure for pattern matching (Allauzen et al., 1999)
- Indexing compressed text (Ferragina and Manzini, 2005)
- Chin-Wan Chung, Chong-Kwon Kim, Won Kim, Web Communication Technologies and Internet-Related Social Issues - HSI 2003 (Springer, 2003)
- Xuejia Lai, Dawu Gu, Bo Jin, Forensics in Telecommunications, Information and Multimedia (Springer, 2011)
- Michael T. Goodrich, Roberto Tamassia, Data Structures and Algorithms in Java (Wiley, 1998)
- Dan Gusfield, Algorithms on Strings, Trees, and Sequences (Cambridge University Press, 1997)