Skip to content

Commit 4ab67d6

Browse files
refactor: use Set for removeDuplicates to reduce from O(n^2) to O(n)
1 parent 019519b commit 4ab67d6

2 files changed

Lines changed: 14 additions & 30 deletions

File tree

‎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^2) - inner loop checks all unique items for each element
5+
* Space Complexity: O(n) - stores unique items in array
6+
* Optimal Time Complexity: O(n) - using a Set for O(1) lookups
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

‎Sprint-1/Python/remove_duplicates/remove_duplicates.py‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,16 @@ def remove_duplicates(values: Sequence[ItemType]) -> List[ItemType]:
77
"""
88
Remove duplicate values from a sequence, preserving the order of the first occurrence of each value.
99
10-
Time complexity:
11-
Space complexity:
12-
Optimal time complexity:
10+
Time complexity: O(n^2) - inner loop checks all unique items for each element
11+
Space complexity: O(n) - stores unique items in list
12+
Optimal time complexity: O(n) - using a set for O(1) lookups
1313
"""
14+
seen = set()
1415
unique_items = []
1516

1617
for value in values:
17-
is_duplicate = False
18-
for existing in unique_items:
19-
if value == existing:
20-
is_duplicate = True
21-
break
22-
if not is_duplicate:
18+
if value not in seen:
19+
seen.add(value)
2320
unique_items.append(value)
2421

2522
return unique_items

0 commit comments

Comments
 (0)