Sheffield | 25-SDC-Nov | Sheida Shabankari | Sprint 2 |Improve code with precomputing#113
Conversation
cjyuan
left a comment
There was a problem hiding this comment.
Can you use complexity to explain why your implementation is an improvement?
| # Precompute prefix hashes for each string to speed up comparisons | ||
| prefix_map={s:[hash(s[:i+1]) for i in range(len(s))] for s in strings} |
There was a problem hiding this comment.
How do these "prefix hashes" speed up comparison?
There was a problem hiding this comment.
At first, I thought the exercise needed me to precompute and keep some data for each string. So I used prefix hashes, thinking this would avoid comparing letters one by one and make the function much faster.
But after testing, I saw that using hashes did not make it much faster. Sorting the strings and comparing only neighbors worked better, was simpler, and gave the speed improvement needed.
There was a problem hiding this comment.
Note: With the way you used prefix hashes, the complexity actually became higher (when the length of each string is large).
|
Hi CJ,Thanks for your feedback. Previously, for each character in the string (O(n)), the code performed a membership check on the entire string (O(n)), resulting in O(n²) complexity. By precomputing a set of all lowercase characters once (O(n)) and using O(1) set lookups inside the loop, the overall complexity is reduced to O(n) . |
|
Can you also do a complexity analysis for |
PR summary :
These changes make the function much faster while keeping all existing tests passing, including the large list test.