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 *
8- * @param {Array } inputSequence - Sequence to remove duplicates from
9- * @returns {Array } New sequence with duplicates removed
8+ * Original complexity:
9+ * The original solution uses nested loops. For each item in
10+ * the input sequence, it searches through the uniqueItems
11+ * array to check whether the value already exists. This
12+ * results in O(n²) time complexity in the worst case.
13+ *
14+ * Refactor:
15+ * Use a Set to keep track of values that have already been
16+ * seen. Set.has() and Set.add() are O(1) operations, allowing
17+ * us to process the sequence in a single loop.
18+ *
19+ * Refactored Complexity:
20+ * Time Complexity: O(n)
21+ * Space Complexity: O(n)
1022 */
1123export function removeDuplicates ( inputSequence ) {
24+ const seen = new Set ( ) ;
1225 const uniqueItems = [ ] ;
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 ] ) ;
27+ for ( const item of inputSequence ) {
28+ if ( ! seen . has ( item ) ) {
29+ seen . add ( item ) ;
30+ uniqueItems . push ( item ) ;
3231 }
3332 }
3433
3534 return uniqueItems ;
36- }
35+ }
0 commit comments