|
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 | + * Time Complexity: O(n²) |
| 5 | + * Space Complexity: O(n) |
| 6 | + * Optimal Time Complexity: O(n) |
| 7 | + * Explanation: The function checks each element against all previously seen elements to determine, |
| 8 | + * if it is a duplicate, resulting in a time complexity of O(n²) in the worst case. |
| 9 | + * The space complexity is O(n) because we are storing unique items in a new array. |
| 10 | + * The optimal time complexity can be achieved by using a Set to track seen items, |
| 11 | + * which allows for O(1) average time complexity for lookups, resulting in an overall time complexity of O(n). |
| 12 | + * Refactor: Using Set allows to constant-time membership checks, which significantly reduces the time complexity from O(n²) to O(n). |
7 | 13 | * |
8 | 14 | * @param {Array} inputSequence - Sequence to remove duplicates from |
9 | 15 | * @returns {Array} New sequence with duplicates removed |
10 | 16 | */ |
11 | 17 | export function removeDuplicates(inputSequence) { |
| 18 | + const seen = new Set(); |
12 | 19 | 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]); |
| 20 | + for (const item of inputSequence) { |
| 21 | + if (!seen.has(item)) { |
| 22 | + seen.add(item); |
| 23 | + uniqueItems.push(item); |
32 | 24 | } |
33 | 25 | } |
34 | | - |
35 | 26 | return uniqueItems; |
36 | 27 | } |
0 commit comments