Skip to problem
←

Boyer–Moore Pattern Search

Hard 0 attempts

Using the Boyer–Moore string-matching technique, find every occurrence of pattern in text. Return the zero-based starting indices in ascending order, including overlapping matches. Return an empty array when there are no matches.

Use JavaScript string indexing (UTF-16 code units). The bad-character heuristic is sufficient for this exercise.

Function contract

Implement boyerMoore(text, pattern) for two non-empty strings. Indices use JavaScript UTF-16 code units.

Output: All zero-based starting indices where pattern occurs, in ascending order, including overlapping matches. Return [] if none exist.

Example 1

Input
text = "ABAAABCD"
pattern = "ABC"
Output
[4]

Example 2

Input
text = "AAAAA"
pattern = "AAA"
Output
[0,1,2]
Constraints
  • 1 <= text.length <= 10^5
  • 1 <= pattern.length <= text.length

Boyer-Moore Bad Character Heuristic

Precompute bad character table to skip alignments.

javascript
function boyerMoore(text, pattern) {
  const m = pattern.length,
    n = text.length,
    result = [];
  const badChar = {};
  for (let i = 0; i < m; i++) badChar[pattern[i]] = i;
  let s = 0;
  while (s <= n - m) {
    let j = m - 1;
    while (j >= 0 && pattern[j] === text[s + j]) j--;
    if (j < 0) {
      result.push(s);
      s += s + m < n ? m - (badChar[text[s + m]] ?? -1) : 1;
    } else s += Math.max(1, j - (badChar[text[s + j]] ?? -1));
  }
  return result;
}

Time: O(m + n/m) in the best case, including preprocessing; O(nm) in the worst case for the bad-character-only variant. Here n is text length and m is pattern length. Space: O(min(m, alphabet size)) for the last-occurrence table, excluding output.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript