Optimizing Exact String Matching via Statistical Anchoring
Omar Garraoui
TL;DR
This work tackles exact string matching in natural language text and aims to reduce character comparisons by reordering verification. It introduces a preprocessing step that identifies a statistically rare anchor in the pattern using a frequency table $freq(c)$ and then verifies at $a = \arg\min_{i \in [0, m-1]} freq(P[i])$ before other positions, while preserving the Horspool shift heuristic. The algorithm maintains $O(m)$ preprocessing and $O(n/m)$ average-case search, and in experiments on Italian text yields $5.33\%$ fewer comparisons than standard BMH (303{,}194 vs 320{,}275) with a $100\%$ win rate across $12$ patterns; gains are most pronounced for patterns containing rare characters. The approach is simple to integrate, scalable to large corpora, and demonstrates that domain-specific statistics can yield meaningful practical speedups without increasing asymptotic complexity.
Abstract
In this work, we propose an enhancement to the Boyer-Moore-Horspool algorithm tailored for natural language text. The approach involves preprocessing the search pattern to identify its statistically least frequent character, referred to as the "anchor." During the search, verification is first performed at this high-entropy position, allowing the algorithm to quickly discard non-matching windows. This fail-fast strategy reduces unnecessary comparisons, improving overall efficiency. Our implementation shows that incorporating basic linguistic statistics into classical pattern-matching techniques can boost performance without increasing complexity to the shift heuristics.
