1- /**
2- * Remove duplicate values from a sequence, preserving the order of the first occurrence of each value.
1+
2+ /**
3+ * Remove duplicate values from a sequence, preserving the order of the first occurrence.
34 *
45 * Time Complexity:
6+ * Before refactoring: O(n^2)
7+ * The original solution used nested loops to check for duplicates.
8+ * After refactoring: O(n)
9+ * Using a Set allows duplicate checks in constant time (O(1)),
10+ * removing the need for the inner loop.
11+ *
512 * Space Complexity:
6- * Optimal Time Complexity:
13+ * Before refactoring: O(n)
14+ * The result array could store up to n unique items.
15+ * After refactoring: O(n)
16+ * The Set and the final array both store up to n unique items.
717 *
18+ * Optimal Time Complexity:
19+ * O(n) — You must inspect each element at least once, and Set lookups are O(1).
20+ *
821 * @param {Array } inputSequence - Sequence to remove duplicates from
922 * @returns {Array } New sequence with duplicates removed
1023 */
1124export function removeDuplicates ( inputSequence ) {
12- const uniqueItems = [ ] ;
25+ const uniques = new Set ( ) //does dupliacte check in O(1)
1326
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 ] ) ;
32- }
27+ for ( let i = 0 ; i < inputSequence . length ; i ++ ) { // O(n)
28+ uniques . add ( inputSequence [ i ] ) ;
3329 }
34-
35- return uniqueItems ;
36- }
30+ return Array . from ( uniques ) ;
31+ }
0 commit comments