-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathremoveDuplicates.mjs
More file actions
27 lines (25 loc) · 769 Bytes
/
removeDuplicates.mjs
File metadata and controls
27 lines (25 loc) · 769 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Remove duplicate values from a sequence, preserving the order of the first occurrence of each value.
*
* Areas of inefficiency in original version:
* - Nested loop: for each element in inputSequence, it scanned uniqueItems so far.
* That creates quadratic behavior in the worst case.
*
* Time Complexity: O(n²)
* Space Complexity:O(n)
* Optimal Time Complexity:
*
* @param {Array} inputSequence - Sequence to remove duplicates from
* @returns {Array} New sequence with duplicates removed
*/
export function removeDuplicates(inputSequence) {
const seen = new Set();
const uniqueItems = [];
for (const item of inputSequence) {
if (!seen.has(item)) {
seen.add(item);
uniqueItems.push(item);
}
}
return uniqueItems;
}