-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathremoveDuplicates.mjs
More file actions
29 lines (27 loc) · 799 Bytes
/
removeDuplicates.mjs
File metadata and controls
29 lines (27 loc) · 799 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
28
29
/**
* Remove duplicate values from a sequence, preserving the order of the first occurrence of each value.
*
* Time Complexity:
* ANSWER:O(n)
Because the array is looped through once.
* Space Complexity:
ANSWER:O(n)
Because a Set is used to track seen items.
* Optimal Time Complexity:
ANSWER:O(n)
Each item is processed once using a Set for lookup.
*
* @param {Array} inputSequence - Sequence to remove duplicates from
* @returns {Array} New sequence with duplicates removed
*/
export function removeDuplicates(inputSequence) {
const seen = new Set();
const result = [];
for (const item of inputSequence) {
if (!seen.has(item)) {
seen.add(item);
result.push(item);
}
}
return result;
}