Skip to content

Commit 45299ad

Browse files
refactor: replace nested loop O(n^2) duplicate removal with O(n) Set-based implementation
1 parent 6c5bcf5 commit 45299ad

File tree

1 file changed

+8
-21
lines changed

1 file changed

+8
-21
lines changed

Sprint-1/JavaScript/removeDuplicates/removeDuplicates.mjs

Lines changed: 8 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,21 @@
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)
77
*
88
* @param {Array} inputSequence - Sequence to remove duplicates from
99
* @returns {Array} New sequence with duplicates removed
1010
*/
1111
export function removeDuplicates(inputSequence) {
12+
const seen = new Set();
1213
const uniqueItems = [];
1314

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]);
15+
for (const item of inputSequence) {
16+
if (!seen.has(item)) {
17+
seen.add(item);
18+
uniqueItems.push(item);
3219
}
3320
}
3421

0 commit comments

Comments
 (0)