Skip to content

Commit 488f1c5

Browse files
committed
ref: refactor Levenshtein distance implementation
- Rewrite the original levenshtein distance implementation in functional style - Add optimized version of levenshtein distance
1 parent 1e2d7e9 commit 488f1c5

File tree

2 files changed

+83
-39
lines changed

2 files changed

+83
-39
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,82 @@
11
package com.thealgorithms.dynamicprogramming;
22

3+
import java.util.stream.IntStream;
4+
35
/**
4-
* @author Kshitij VERMA (github.com/kv19971) LEVENSHTEIN DISTANCE dyamic
5-
* programming implementation to show the difference between two strings
6-
* (https://en.wikipedia.org/wiki/Levenshtein_distance)
6+
* Provides functions to calculate the Levenshtein distance between two strings.
7+
*
8+
* The Levenshtein distance is a measure of the similarity between two strings by calculating the minimum number of single-character
9+
* edits (insertions, deletions, or substitutions) required to change one string into the other.
710
*/
811
public class LevenshteinDistance {
912

10-
private static int minimum(int a, int b, int c) {
11-
if (a < b && a < c) {
12-
return a;
13-
} else if (b < a && b < c) {
14-
return b;
15-
} else {
16-
return c;
17-
}
13+
/**
14+
* Calculates the Levenshtein distance between two strings using a naive dynamic programming approach.
15+
*
16+
* This function computes the Levenshtein distance by constructing a dynamic programming matrix and iteratively filling it in.
17+
* It follows the standard top-to-bottom, left-to-right approach for filling in the matrix.
18+
*
19+
* @param string1 The first string.
20+
* @param string2 The second string.
21+
* @return The Levenshtein distance between the two input strings.
22+
*
23+
* Time complexity: O(nm),
24+
* Space complexity: O(nm),
25+
*
26+
* where n and m are lengths of `string1` and `string2`.
27+
*
28+
* Note that this implementation uses a straightforward dynamic programming approach without any space optimization.
29+
* It may consume more memory for larger input strings compared to the optimized version.
30+
*/
31+
public static int naiveLevenshteinDistance(String string1, String string2) {
32+
int[][] distanceMatrix = IntStream.rangeClosed(0, string1.length()).mapToObj(i -> IntStream.rangeClosed(0, string2.length()).map(j -> (i == 0) ? j : (j == 0) ? i : 0).toArray()).toArray(int[][] ::new);
33+
34+
IntStream.range(1, string1.length() + 1).forEach(i -> IntStream.range(1, string2.length() + 1).forEach(j -> {
35+
int cost = (string1.charAt(i - 1) == string2.charAt(j - 1)) ? 0 : 1;
36+
distanceMatrix[i][j] = Math.min(distanceMatrix[i - 1][j - 1] + cost, Math.min(distanceMatrix[i][j - 1] + 1, distanceMatrix[i - 1][j] + 1));
37+
}));
38+
39+
return distanceMatrix[string1.length()][string2.length()];
1840
}
1941

20-
public static int calculateLevenshteinDistance(String str1, String str2) {
21-
int len1 = str1.length() + 1;
22-
int len2 = str2.length() + 1;
23-
int[][] distanceMat = new int[len1][len2];
24-
for (int i = 0; i < len1; i++) {
25-
distanceMat[i][0] = i;
26-
}
27-
for (int j = 0; j < len2; j++) {
28-
distanceMat[0][j] = j;
42+
/**
43+
* Calculates the Levenshtein distance between two strings using an optimized dynamic programming approach.
44+
*
45+
* This edit distance is defined as 1 point per insertion, substitution, or deletion required to make the strings equal.
46+
*
47+
* @param string1 The first string.
48+
* @param string2 The second string.
49+
* @return The Levenshtein distance between the two input strings.
50+
*
51+
* Time complexity: O(nm),
52+
* Space complexity: O(n),
53+
*
54+
* where n and m are lengths of `string1` and `string2`.
55+
*
56+
* Note that this implementation utilizes an optimized dynamic programming approach, significantly reducing the space complexity from O(nm) to O(n), where n and m are the lengths of `string1` and `string2`.
57+
*
58+
* Additionally, it minimizes space usage by leveraging the shortest string horizontally and the longest string vertically in the computation matrix.
59+
*/
60+
public static int optimizedLevenshteinDistance(String string1, String string2) {
61+
if (string1.isEmpty()) {
62+
return string2.length();
2963
}
30-
for (int i = 1; i < len1; i++) {
31-
for (int j = 1; j < len2; j++) {
32-
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
33-
distanceMat[i][j] = distanceMat[i - 1][j - 1];
34-
} else {
35-
distanceMat[i][j] = 1 + minimum(distanceMat[i - 1][j], distanceMat[i - 1][j - 1], distanceMat[i][j - 1]);
36-
}
64+
65+
int[] previousDistance = IntStream.rangeClosed(0, string1.length()).toArray();
66+
67+
for (int j = 1; j <= string2.length(); j++) {
68+
int prevSubstitutionCost = previousDistance[0];
69+
previousDistance[0] = j;
70+
71+
for (int i = 1; i <= string1.length(); i++) {
72+
int deletionCost = previousDistance[i] + 1;
73+
int insertionCost = previousDistance[i - 1] + 1;
74+
int substitutionCost = (string1.charAt(i - 1) == string2.charAt(j - 1)) ? prevSubstitutionCost : prevSubstitutionCost + 1;
75+
prevSubstitutionCost = previousDistance[i];
76+
previousDistance[i] = Math.min(deletionCost, Math.min(insertionCost, substitutionCost));
3777
}
3878
}
39-
return distanceMat[len1 - 1][len2 - 1];
40-
}
41-
42-
public static void main(String[] args) {
43-
String str1 = ""; // enter your string here
44-
String str2 = ""; // enter your string here
4579

46-
System.out.print("Levenshtein distance between " + str1 + " and " + str2 + " is: ");
47-
System.out.println(calculateLevenshteinDistance(str1, str2));
80+
return previousDistance[string1.length()];
4881
}
4982
}

src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java

+15-4
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,20 @@
88
public class LevenshteinDistanceTests {
99

1010
@ParameterizedTest
11-
@CsvSource({"dog,cat,3", "sunday,saturday,3", "cat,cats,1", "rain,train,1"})
12-
void levenshteinDistanceTest(String str1, String str2, int distance) {
13-
int result = LevenshteinDistance.calculateLevenshteinDistance(str1, str2);
14-
assertEquals(distance, result);
11+
@CsvSource({// String 1, String 2, Expected Distance
12+
"'', '', 0", "'Hello, World!', 'Hello, World!', 0", "'', 'Rust', 4", "horse, ros, 3", "tan, elephant, 6", "execute, intention, 8"})
13+
void
14+
naiveLevenshteinDistanceTest(String str1, String str2, int expectedDistance) {
15+
int result = LevenshteinDistance.naiveLevenshteinDistance(str1, str2);
16+
assertEquals(expectedDistance, result);
17+
}
18+
19+
@ParameterizedTest
20+
@CsvSource({// String 1, String 2, Expected Distance
21+
"'', '', 0", "'Hello, World!', 'Hello, World!', 0", "'', 'Rust', 4", "horse, ros, 3", "tan, elephant, 6", "execute, intention, 8"})
22+
void
23+
optimizedLevenshteinDistanceTest(String str1, String str2, int expectedDistance) {
24+
int result = LevenshteinDistance.optimizedLevenshteinDistance(str1, str2);
25+
assertEquals(expectedDistance, result);
1526
}
1627
}

0 commit comments

Comments
 (0)