|
1 | 1 | /** |
2 | 2 | * Remove duplicate values from a sequence, preserving the order of the first occurrence of each value. |
3 | 3 | * |
4 | | - * Time Complexity: |
5 | | - * Space Complexity: |
6 | | - * Optimal Time Complexity: |
| 4 | +/** |
| 5 | +* Originally (nested loops): |
| 6 | +* Time Complexity: O(n²) - the outer loop runs n times and the inner loop |
| 7 | +* scans uniqueItems, which can grow up to n items (about n(n - 1) / 2 |
| 8 | +* checks in the worst case, when all items are unique) |
| 9 | +* Space Complexity: O(n) - uniqueItems can hold up to n items |
| 10 | +* Optimal Time Complexity: O(n) - every item must be read at least once, and |
| 11 | +* a Set gives O(1) average lookups |
| 12 | +
|
| 13 | +* After refactor ([...new Set(inputSequence)]): |
| 14 | +* Time Complexity: O(n) - building the Set visits each item once with O(1) |
| 15 | +* average inserts; spreading it into an array is also O(n) |
| 16 | +* Space Complexity: O(n) - the Set and the result array each hold up to n items |
| 17 | +* Optimal Time Complexity: O(n) - every item must be read at least once, so we |
| 18 | +* can't do better than linear |
| 19 | +* / |
| 20 | + * |
7 | 21 | * |
8 | 22 | * @param {Array} inputSequence - Sequence to remove duplicates from |
9 | 23 | * @returns {Array} New sequence with duplicates removed |
10 | 24 | */ |
11 | 25 | export function removeDuplicates(inputSequence) { |
12 | | - const uniqueItems = []; |
13 | | - |
14 | | - for ( |
15 | | - let currentIndex = 0; |
16 | | - currentIndex < inputSequence.length; |
17 | | - currentIndex++ |
18 | | - ) { |
19 | | - let isDuplicate = false; |
20 | | - for ( |
21 | | - let compareIndex = 0; |
22 | | - compareIndex < uniqueItems.length; |
23 | | - compareIndex++ |
24 | | - ) { |
25 | | - if (inputSequence[currentIndex] === uniqueItems[compareIndex]) { |
26 | | - isDuplicate = true; |
27 | | - break; |
28 | | - } |
29 | | - } |
30 | | - if (!isDuplicate) { |
31 | | - uniqueItems.push(inputSequence[currentIndex]); |
32 | | - } |
33 | | - } |
34 | | - |
35 | | - return uniqueItems; |
| 26 | + |
| 27 | + return [... new Set(inputSequence)]; |
36 | 28 | } |
0 commit comments