Glasgow | 26- SDC-Mar | Taras Mykytiuk | Sprint 1 | Analyse and Refactor Functions#166
Glasgow | 26- SDC-Mar | Taras Mykytiuk | Sprint 1 | Analyse and Refactor Functions#166TarasMykytiuk wants to merge 3 commits into
Conversation
| * Time Complexity: before fix O(2N), after double loop removed - O(N) | ||
| * Space Complexity: 0(N) - depends on numbers.length | ||
| * Optimal Time Complexity: O(N) |
There was a problem hiding this comment.
- In complexity analysis, O(2N) is the same as O(N).
- In practice, combining code in two loops into one could help improve the performance, but rarely make the function run twice as fast.
- In space complexity analysis, the space usually refers to the auxiliary space (extra memory) used by the algorithm in addition to the input itself.
| export const findCommonItems = (firstArray, secondArray) => { | ||
| const firstSet = new Set(firstArray); | ||
| const secondSet = new Set(secondArray); | ||
| secondArray = [...secondSet].filter((element) => firstSet.has(element)) |
There was a problem hiding this comment.
Note: Most set implementation supports typical set operations like union and intersect. You could also explore using them.
| * Time Complexity: | ||
| * Space Complexity: | ||
| * Optimal Time Complexity: | ||
| * Time Complexity: worst O(N!) - factorial |
There was a problem hiding this comment.
How did you derive the complexity of O(N!)?
N! = N * (N-1) * (N-2) * ... * 2 * 1
| if (numbers[i] + numbers[j] === target) { | ||
| return true; | ||
| } | ||
| if (numbers.includes(target - numbers[i])) { |
There was a problem hiding this comment.
What is the complexity of numbers.includes()?
| inputSequence.forEach((element) => { | ||
| if (!uniqueItems.includes(element)) { | ||
| uniqueItems.push(element); |
There was a problem hiding this comment.
The complexity of this implementation is still O(N*N). Can you figure out why?
| return common_items | ||
| firstSet = set(first_sequence) | ||
| secondSet = set(first_sequence) | ||
| return list(firstSet.intersection(secondSet)) |
| for j in range(i + 1, len(numbers)): | ||
| if numbers[i] + numbers[j] == target_sum: | ||
| return True | ||
| if (numbers[i] - target_sum) in numbers: |
There was a problem hiding this comment.
Could you look up the complexity of in operation on a list (numbers is a list) in Python?
| if value not in unique_items: | ||
| unique_items.append(value) |
There was a problem hiding this comment.
unique_items is a list, so the complexity of the in operation on line 18 is not O(1).
Learners, PR Template
Self checklist
Changelist
Exercises for js and python are done.