Skip to content

Commit c165a71

Browse files
committed
Refactor removeDuplicates from O(n²) to O(n) using a Set
1 parent 749e9e0 commit c165a71

1 file changed

Lines changed: 19 additions & 27 deletions

File tree

Lines changed: 19 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,28 @@
11
/**
22
* Remove duplicate values from a sequence, preserving the order of the first occurrence of each value.
33
*
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+
*
721
*
822
* @param {Array} inputSequence - Sequence to remove duplicates from
923
* @returns {Array} New sequence with duplicates removed
1024
*/
1125
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)];
3628
}

0 commit comments

Comments
 (0)