Skip to content

Commit efbf151

Browse files
committed
feat: optimise removeDuplicates function to reduce time complexity
1 parent 4cbe96b commit efbf151

1 file changed

Lines changed: 11 additions & 25 deletions

File tree

Lines changed: 11 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,22 @@
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**2)
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 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]);
12+
const seenItems = new Set();
13+
let result = [];
14+
// The initial solution was a nested loop, with a time complexity of O(n**2). This was optimised by using a set to track seen items, thereby reducing the complexity to O(n)
15+
for (const item of inputSequence) {
16+
if (!seenItems.has(item)) {
17+
seenItems.add(item);
18+
result.push(item);
3219
}
3320
}
34-
35-
return uniqueItems;
21+
return result;
3622
}

0 commit comments

Comments
 (0)