@@ -306,43 +306,25 @@ def levenshtein_distance(s1: str, s2: str) -> int:
306306 len1 = len (s1 )
307307 len2 = len (s2 )
308308 # Use a preallocated list instead of creating a new list every iteration
309-
310- # Early exit for empty string cases
311- if len1 == 0 :
312- return len2
313- if len2 == 0 :
314- return len1
315-
316- # Convert strings to lists for fast indexed access
317- s1_list = list (s1 )
318- s2_list = list (s2 )
319-
320- # Preallocate and reuse arrays; avoid creating new ones every iteration
321309 previous = list (range (len1 + 1 ))
322310 current = [0 ] * (len1 + 1 )
323311
324312 for index2 in range (len2 ):
325- char2 = s2_list [index2 ]
313+ char2 = s2 [index2 ]
326314 current [0 ] = index2 + 1
327-
328- # Remove redundant intermediate assignments for better cache locality
329- prev = previous
330- curr = current
331- s1_chars = s1_list
332- # Use local variables for frequently accessed values
333315 for index1 in range (len1 ):
334- # Unrolling char1 assignment and equality check
335- if s1_chars [ index1 ] == char2 :
336- curr [index1 + 1 ] = prev [index1 ]
316+ char1 = s1 [ index1 ]
317+ if char1 == char2 :
318+ current [index1 + 1 ] = previous [index1 ]
337319 else :
338- x = prev [ index1 ]
339- y = prev [index1 + 1 ]
340- z = curr [index1 ]
341- min_xy = min ( x , y )
342- min_xyz = min (z , min_xy )
343- curr [ index1 + 1 ] = 1 + min_xyz
344-
345- # Swap references rather than copying data
320+ # Fast min calculation without tuple construct
321+ a = previous [index1 ]
322+ b = previous [index1 + 1 ]
323+ c = current [ index1 ]
324+ min_val = min (b , a )
325+ min_val = min ( c , min_val )
326+ current [ index1 + 1 ] = 1 + min_val
327+ # Swap references instead of copying
346328 previous , current = current , previous
347329 return previous [len1 ]
348330
0 commit comments