London | 25-SDC-July | Rihanna Poursoltani | Sprint 2 | Improve code with precomputing#89
Conversation
cjyuan
left a comment
There was a problem hiding this comment.
Code looks good. Can you explain using big-O notation why your approach is better?
Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py
Outdated
Show resolved
Hide resolved
Using a set makes membership checks O(1) on average. Creating the set takes O(n) and we iterate over at most n unique characters, so the overall complexity is O(n). |
Can you also do the same for |
Sorting the strings takes O(n log n). After sorting, we only compare adjacent strings, and each prefix comparison takes O(m) ( m is the length of the shorter string). This results in O(n·m) for the comparisons. Overall complexity is O(n log n + n·m), which is better than comparing every pair of strings (O(n²·m)). |
|
If we are factoring in the length of the strings, |
You’re right. so sorting and comparison cost is O(m · n log n) |
|
Yes. O(m · n log n) O(n log n · m) may be misinterpreted as O(n log (n · m)). |
Learners, PR Template
Self checklist
Changelist
For optimising I tried to
Questions
No question