Algorithms

Boyer–Moore–Horspool substring search

You look for ABAC in a row of letters. The character under the end of the pattern is X, which appears nowhere in ABAC. A one-position move would leave X inside the next window, so that window would fail too. Horspool’s algorithm uses this observation to skip several starting positions in one move.

Compare and shift

Comparisons 0
TextXXBXABABACPatternABACPossible starts1234567

Compare the first window from right to left.

Windows checked 0 · Starts skipped 0 · Matches —

Shift table

A
1
B
2
Other characters
4

Video walkthrough

Read the window from right to left

A window covers as many characters as the pattern. Align the pattern with the first window, then compare pairs from right to left until a pair differs or the whole pattern matches.

For the shift, read the text character under the last position of the pattern. That right-edge character determines the move even if the mismatch was farther left. After a match, use the same rule to look for further occurrences.

Build the table from every pattern character before its last position. Record the distance from each character to the last position. If a character occurs more than once, keep the distance from its rightmost occurrence before the end. Any character missing from the table gets the full pattern length.

Six comparisons in XXBXABABAC

For ABAC the table gives A a shift of 1 and B a shift of 2. C and all other characters get 4. In the first window XXBX, X at the right edge differs from C. Shift four positions to start 5.

The next window is ABAB. The rightmost B differs from C, so shift two positions to start 7. The window now reads ABAC and all four comparisons succeed. The search makes six character comparisons and skips four valid starting positions.

Why the shift is safe

For a move shorter than the pattern length, the old window’s right-edge character stays under the pattern and moves to an earlier pattern position. A match can occur only if the pattern has that character at the new position. The shift table gives the smallest move that could make this happen.

This argument also holds after a match. Try ABABABA with ABA in the player. The shift after the first match is 2 and the algorithm finds matches starting at positions 1, 3 and 5.

JavaScript implementation

The function returns all match positions starting at 1 and the number of character comparisons in the text. Both strings are split into Unicode code points with Array.from.

For a pattern of length m, building the table takes O(m) time with expected constant-time Map operations. The table stores one entry per distinct character before the pattern’s end. The worst case for the search is O((n − m + 1)m) when the text length n is at least m. For example, searching for BAAA in a row of A characters can require four comparisons and a one-position shift at every window. Converting the strings to arrays uses O(n + m) extra space.

Show executable code
function horspoolSearch(text, pattern) {
    const source = Array.from(text);
    const target = Array.from(pattern);
    const size = target.length;
    if (!size) throw new RangeError("The pattern must not be empty");

    const shifts = new Map();
    for (let j = 0; j < size - 1; j++) {
        shifts.set(target[j], size - 1 - j);
    }

    const positions = [];
    let comparisons = 0;
    for (let start = 0; start + size <= source.length;) {
        let j = size - 1;
        while (j >= 0) {
            comparisons++;
            if (source[start + j] !== target[j]) break;
            j--;
        }
        if (j < 0) positions.push(start + 1);
        const rightEdge = source[start + size - 1];
        start += shifts.get(rightEdge) ?? size;
    }
    return { positions, comparisons };
}

Further reading

R. Nigel Horspool — Practical Fast Searching in Strings

Substring search and the KMP algorithm