1+ /*
2+ Input: word1 = "sea", word2 = "eat"
3+ Output: 2
4+ Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
5+ */
6+
7+
8+ function min ( i , j ) {
9+ return i > j ? j : i ;
10+ }
11+
12+ function max ( i , j ) {
13+ return i > j ? i : j ;
14+ }
15+
16+ function solve ( w1 , w2 , dp , i , j ) {
17+ // If we have traversed both the strings till the end at the same time,
18+ // that means there are no extra characters, so return 0.
19+ // (Is being handled by the below base case but just added to minimize a max
20+ // operation on some large string sizes)
21+ if ( i == w1 . length && j == w2 . length ) return 0 ;
22+
23+ // If one of the strings is traversed completely before the other,
24+ // that means there are some extra characters in the other string,
25+ // so we add the remaining length to our steps count.
26+ if ( i == w1 . length || j == w2 . length ) return max ( w1 . length - i , w2 . length - j ) ;
27+
28+
29+ // return the cached value.
30+ if ( dp [ i ] [ j ] != - 1 ) return dp [ i ] [ j ] ;
31+
32+ // if both characters are same that means no need to remove those characters
33+ // from both the strings, so just increment the pointer for both strings.
34+ if ( w1 [ i ] == w2 [ j ] ) return solve ( w1 , w2 , dp , i + 1 , j + 1 ) ;
35+
36+ // otherwise we add one to the step count and solve for minimum steps
37+ // from the options of removing from string w1 or w2.
38+ return dp [ i ] [ j ] = 1 + min ( solve ( w1 , w2 , dp , i + 1 , j ) , solve ( w1 , w2 , dp , i , j + 1 ) ) ;
39+ }
40+ function minDistance ( word1 , word2 ) {
41+ let dp = Array ( word1 . length + 1 ) . fill ( ) . map ( ( ) => Array ( word2 . length + 1 ) . fill ( - 1 ) )
42+ return solve ( word1 , word2 , dp , 0 , 0 ) ;
43+ }
44+
45+
46+ let s1 = "sea" ;
47+ let s2 = "eat" ;
48+ console . log ( minDistance ( s1 , s2 ) ) ;
0 commit comments