Skip to content

Commit d1d59ab

Browse files
committed
Refactor finding longest common prefix
1 parent cf45392 commit d1d59ab

File tree

1 file changed

+4
-9
lines changed

1 file changed

+4
-9
lines changed

Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,28 +15,23 @@ def find_longest_common_prefix(strings: List[str]):
1515

1616
longest = ""
1717

18-
# Precompute prefix hashes for each string to speed up comparisons
19-
prefix_map={s:[hash(s[:i+1]) for i in range(len(s))] for s in strings}
20-
2118
# Compare only adjacent strings in the sorted list
2219
for i in range(len(strings)-1):
23-
common=find_common_prefix(strings[i],strings[i+1],prefix_map)
20+
common=find_common_prefix(strings[i],strings[i+1])
2421
if len(common)>len(longest):
2522
longest=common
2623

2724
return longest
2825

2926

30-
def find_common_prefix(left: str, right: str,prefix_map:dict) -> str:
27+
def find_common_prefix(left: str, right: str) -> str:
3128
# Retrieve precomputed prefix hashes
32-
left_hashes=prefix_map[left]
33-
right_hashes=prefix_map[right]
34-
min_length = min(len(left_hashes), len(right_hashes))
29+
min_length = min(len(left), len(right))
3530

3631
common_len = 0
3732
# Compare hashes until a mismatch is found
3833
for i in range(min_length):
39-
if left_hashes[i] == right_hashes[i]:
34+
if left[i] == right[i]:
4035
common_len=i+1
4136
else:
4237
break

0 commit comments

Comments
 (0)