Boyer Moore Algorithm for Pattern Searching

Pattern: Pattern matching

hard

Compare the pattern with the text from the pattern's right end. On a mismatch, shift the pattern so the text's bad character lines up with its last copy in the pattern, or past it if the pattern does not contain it. Often whole stretches of text are skipped.

The problem

Given a text and a pattern, return every index where the pattern starts in the text, in increasing order, using the Boyer-Moore bad-character rule. Indexes count from 0 and matches may overlap. For example, "ABAAABCD" with "ABC" gives [4], and "AABAACAADAABAABA" with "AABA" gives [0, 9, 12].

The link above is a GeeksforGeeks article. The function name boyerMoore is this guide's own. Full Boyer-Moore also has a "good suffix" rule, which this guide leaves out.

Think first

  • Why compare from the right end of the pattern instead of the left?
  • When the text character at a mismatch is not in the pattern at all, how far can the pattern jump?
  • What if the character is in the pattern, but to the right of the mismatch?

Hints

    Brute force, and why it fails

    Compare at every start from the left: O(n × m). Bad-character shifts are often far larger than 1, but the worst case (as in "aaaa…" with "aa") is still O(n × m).

    The key insight

    Comparing from the right means a mismatch is found at the character that tells you the most. If that character cannot appear in the pattern, every start that would cover it is impossible, so the pattern skips them all.

    Dry run

    A0s
    B1 
    A2 
    A3 
    A4 
    B5 
    C6 
    D7 

    text = ABAAABCD and pattern = ABC. last[A] = 0, last[B] = 1, last[C] = 2. Start with the pattern at s = 0.

    Step 1 of 4

    The plan

    last[c] = last index of c in pattern, or -1
    s = 0
    while s <= n - m:
        j = m - 1
        while j >= 0 and pattern[j] == text[s + j]: j = j - 1
        if j < 0:
            record s
            s = s + (m - last[text[s + m]] if s + m < n else 1)
        else:
            s = s + max(1, j - last[text[s + j]])
    

    Complexity

    Time
    O(n × m) worst, often much less
    Space
    O(alphabet)

    On ordinary text with a long pattern, most shifts are large. On highly repetitive text the shifts can be 1. The last table has one entry per possible character.

    Edge cases

    • Pattern longer than text: no matches.
    • Overlapping matches, as in "aaaaa" with "aa": [0, 1, 2, 3].
    • A bad character that appears later in the pattern than j: the shift would be negative, so use 1.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> boyerMoore(String text, String pattern) {
            int n = text.length(), m = pattern.length();
            int[] last = new int[256];               // last[c] = last index of c in the pattern, or -1
            Arrays.fill(last, -1);
            for (int k = 0; k < m; k++) last[pattern.charAt(k)] = k;
            List<Integer> out = new ArrayList<>();
            int s = 0;                               // where the pattern starts in the text
            while (s <= n - m) {
                int j = m - 1;
                while (j >= 0 && pattern.charAt(j) == text.charAt(s + j)) j--;   // compare from the right
                if (j < 0) {
                    out.add(s);
                    s += s + m < n ? m - last[text.charAt(s + m)] : 1;           // line up the next text character
                } else {
                    s += Math.max(1, j - last[text.charAt(s + j)]);              // bad character: shift past it
                }
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> boyerMoore(string text, string pattern) {
            int n = static_cast<int>(text.size()), m = static_cast<int>(pattern.size());
            int last[256];                           // last[c] = last index of c in the pattern, or -1
            for (int c = 0; c < 256; c++) last[c] = -1;
            for (int k = 0; k < m; k++) last[static_cast<unsigned char>(pattern[k])] = k;
            vector<int> out;
            int s = 0;                               // where the pattern starts in the text
            while (s <= n - m) {
                int j = m - 1;
                while (j >= 0 && pattern[j] == text[s + j]) j--;                 // compare from the right
                if (j < 0) {
                    out.push_back(s);
                    s += s + m < n ? m - last[static_cast<unsigned char>(text[s + m])] : 1;   // line up the next char
                } else {
                    s += max(1, j - last[static_cast<unsigned char>(text[s + j])]);          // bad character shift
                }
            }
            return out;
        }
    };

    Python

    class Solution:
        def boyerMoore(self, text: str, pattern: str) -> list[int]:
            n, m = len(text), len(pattern)
            last = {c: k for k, c in enumerate(pattern)}   # last index of each pattern character
            out, s = [], 0                           # s = where the pattern starts in the text
            while s <= n - m:
                j = m - 1
                while j >= 0 and pattern[j] == text[s + j]:
                    j -= 1                           # compare from the right
                if j < 0:
                    out.append(s)
                    s += m - last.get(text[s + m], -1) if s + m < n else 1   # line up the next text character
                else:
                    s += max(1, j - last.get(text[s + j], -1))               # bad character: shift past it
            return out

    Common mistakes

    • Shifting by j - last[c] without the max(1, …), which can move the pattern backwards.
    • Comparing from the left, which loses the point of the bad-character rule.
    • Reading text[s + m] after a match at the very end of the text.

    Similar problems