Skip to content

fix: Boyer-Moore bad character shift was dead code in for-loop - #14770

Merged
cclauss merged 6 commits into
TheAlgorithms:masterfrom
anyncfunction:fix/boyer-moore-bad-character-shift
Sep 16, 2026
Merged

cclauss merged 6 commits into
TheAlgorithms:masterfrom
anyncfunction:fix/boyer-moore-bad-character-shift

Conversation

@anyncfunction

@anyncfunction anyncfunction commented Jun 7, 2026

Copy link
Copy Markdown
Contributor

Description

The bad_character_heuristic() method used a for-loop with an assignment to the loop variable i, which was immediately overwritten by the next iteration. This caused the algorithm to degrade from O(n/m) to O(n*m) naive search -- the bad character shift was effectively dead code.

Changes

  • Changed for i in range(...) to a while loop so the shift actually takes effect
  • Added max(i + 1, mismatch_index - match_index) guard to prevent backward skips when the mismatched character appears to the right of the mismatch in the pattern
  • Added 3 edge case doctests: no match, overlapping matches, empty text

Verification

All 12 doctests pass:

python -m doctest strings/boyer_moore_search.py

Closes #13039

The bad_character_heuristic() method used a for-loop with an
assignment to the loop variable i, which was immediately
overwritten by the next iteration. This caused the algorithm
to degrade from O(n/m) to O(n*m) naive search.

Changed to a while-loop so the shift actually takes effect.
Added max(i+1, shift) guard to prevent backward skips when
the mismatched character appears to the right of the mismatch
in the pattern. Added edge case doctests.
@algorithms-keeper algorithms-keeper Bot added the tests are failing Do not merge until tests pass label Sep 16, 2026
Fixes the documentation to clarify that 'positions' contains the locations where the pattern was matched.
@algorithms-keeper algorithms-keeper Bot added the awaiting reviews This PR is ready to be reviewed label Sep 16, 2026
Corrected grammatical errors in comments and docstrings.
@cclauss
cclauss merged commit 681929d into TheAlgorithms:master Sep 16, 2026
5 checks passed
@algorithms-keeper algorithms-keeper Bot removed the awaiting reviews This PR is ready to be reviewed label Sep 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tests are failing Do not merge until tests pass

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants