Describe the Boyer-Moore algorithm for string searching.

Instruction: Explain how the Boyer-Moore algorithm works and its advantages over other string search algorithms.

Context: This question aims to evaluate the candidate's understanding of the Boyer-Moore algorithm, known for its efficiency in string searching operations.

Updated

Official answer

Boyer-Moore searches for a pattern by comparing characters from the right end of each aligned pattern window. The window advances through the text; this does not mean scanning the entire text once from right to left.

Preprocessing supplies safe shifts after a mismatch. The bad-character rule uses the mismatched text character's occurrences in the pattern, with a positive shift that cannot skip a possible match. The good-suffix rule uses the suffix already matched: align a suitable earlier occurrence, or align a matching pattern prefix with a suffix of that matched text. If neither exists, a larger shift is safe. Simply moving past every matched suffix when no full earlier occurrence exists can miss overlapping matches.

Take the larger applicable safe shift. Long patterns and a larger effective alphabet often permit substantial skips; small alphabets and repetitive data may reduce them. It is not always faster than KMP or a library search.

Complexity depends on the exact variant, preprocessing and whether all occurrences are reported. Do not attach a universal worst-case linear claim to a bad-character-only implementation. Specify empty-pattern behavior, overlaps and whether positions count bytes, code points or another unit. Benchmark representative text and test repeated-prefix/suffix patterns.

Related Questions