London| 26 March SDC | Jamal Laqdiem | Sprint 1 | Refactor Functions#196
London| 26 March SDC | Jamal Laqdiem | Sprint 1 | Refactor Functions#196jamallaqdiem wants to merge 3 commits into
Conversation
cjyuan
left a comment
There was a problem hiding this comment.
Code is correct.
-
Could you also include the time complexity of the original implementation?
Note: I think "Time Complexity" in the files refers to the time complexity of the original implementation, and "Optimal Time Complexity" refers to the time complexity of the refactored version.
| * Space Complexity:O(n+m) | ||
| * Optimal Time Complexity:O(1) |
There was a problem hiding this comment.
Could you explain how you derived the time complexity of
There was a problem hiding this comment.
Thanks for reviewing, is the the Optimal time complexity that should be O(n+m), we have to spend O(m) time to build the set and O(n) time to filter firstArray.
the space Com should be O(u) to store the matching items.
There was a problem hiding this comment.
What is
| Time Complexity: O(n^3) | ||
| Space Complexity:O(min(n,m)) | ||
| Optimal time complexity: O(n+m) |
There was a problem hiding this comment.
-
Why use
$m$ in the complexity of your algorithm but not in the complexity of the original algorithm? -
How does the algorithm use
$O(min(n, m))$ space?
There was a problem hiding this comment.
You are completely right about the inconsistency between old and new Time complex:
-
let's define n as len(first_sequence) and m as len(second_sequence), if the input sizes differ, m should be used in both.
Original Algorithm: as explained earlier the outer loop runs n times, the inner loop runs m times, and the not in list takes up to O(n) time. Therefore, time complexity of the original code is O(n^2 \cdot m). If we assume n = m, it simplifies to O(n^3).
New Algorithm: Converting the sequences to sets takes O(n) + O(m) time. The Python set intersection '&' average-case time complexity is O(\min(n, m)) as documented in this link :(https://wiki.python.org/moin/TimeComplexity). the overall optimal time complexity of O(n + m). -
Space Complexity Proof for O(\min(n, m)):
the original algorithm allocates memory for the common_items list, an item is only appended to common_items if it exists in both first_sequence and second_sequence
Mathematically, the intersection of two sets cannot contain more elements than the smaller of the two sets
There was a problem hiding this comment.
How much space needed by first_set and second_set?
Self checklist
Changelist
Refactored the scripts js and py to optimise the time and space complexity.