Skip to content

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

Open
anyncfunction wants to merge 1 commit into
TheAlgorithms:masterfrom
anyncfunction:fix/boyer-moore-bad-character-shift
Open

fix: Boyer-Moore bad character shift was dead code in for-loop#14770
anyncfunction wants to merge 1 commit into
TheAlgorithms:masterfrom
anyncfunction:fix/boyer-moore-bad-character-shift

Conversation

@anyncfunction
Copy link
Copy Markdown

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

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant