Skip to content

Fix Levenshtein distance for empty strings - #301

Merged
siriak merged 1 commit into
TheAlgorithms:masterfrom
Navanee45:fix-levenshtein-empty-strings
Nov 18, 2026
Merged

siriak merged 1 commit into
TheAlgorithms:masterfrom
Navanee45:fix-levenshtein-empty-strings

Conversation

@Navanee45

Copy link
Copy Markdown
Contributor

Fixes an edge-case error in levenshtein_distance() when one or both input strings are empty.

The original implementation used loops such as 1:n. When n was zero, R evaluated this as 1:0, causing invalid matrix indexing.

This change:

  • Handles empty strings correctly.
  • Uses seq_len() for safe iteration.
  • Prevents interactive input from running when the file is sourced.
  • Removes problematic invisible characters from the output code.

Tests

Verified the following cases:

levenshtein_distance("kitten", "sitting") == 3
levenshtein_distance("", "") == 0
levenshtein_distance("", "abc") == 3
levenshtein_distance("abc", "") == 3
levenshtein_distance("abc", "abc") == 0

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Sourcing the file interactively still triggers prompts and overwrites variables, while empty-string inputs unnecessarily allocate and fill a large matrix.

2 open issues
What changed in this PR

Updates the repository’s R Levenshtein-distance implementation to handle empty strings correctly and improve input and example handling.

Changes:

  • Uses seq_len() and skips distance-table updates when either input is empty.
  • Adds single-value input validation and character coercion.
  • Gates the example with interactive() and removes invisible characters from the output code.
File Description
string_manipulation/​levenshtein.r Fixes empty-string iteration, validates inputs, and updates the interactive example and output formatting.

Review effort: Balanced

Comment thread string_manipulation/levenshtein.r Resolved
Comment thread string_manipulation/levenshtein.r Resolved

@siriak siriak left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, thanks!

@siriak
siriak merged commit 6430cc8 into TheAlgorithms:master Nov 18, 2026
2 checks passed
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.

3 participants