Skip to content

Commit 1c0d205

Browse files
committed
remove duplicates
1 parent 4db7774 commit 1c0d205

1 file changed

Lines changed: 14 additions & 23 deletions

File tree

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,27 @@
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+
* 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).
713
*
814
* @param {Array} inputSequence - Sequence to remove duplicates from
915
* @returns {Array} New sequence with duplicates removed
1016
*/
1117
export function removeDuplicates(inputSequence) {
18+
const seen = new Set();
1219
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);
3224
}
3325
}
34-
3526
return uniqueItems;
3627
}

0 commit comments

Comments
 (0)