File tree Expand file tree Collapse file tree
Sprint-1/JavaScript/removeDuplicates Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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)
7+ *
8+ * Refactor:
9+ * The original implementation used nested loops to check for duplicates,
10+ * resulting in O(n²) time complexity. Using a Set allows constant-time
11+ * lookups while preserving the insertion order of unique values.
712 *
813 * @param {Array } inputSequence - Sequence to remove duplicates from
914 * @returns {Array } New sequence with duplicates removed
1015 */
1116export function removeDuplicates ( inputSequence ) {
17+ const seen = new Set ( ) ;
1218 const uniqueItems = [ ] ;
1319
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 ] ) ;
20+ for ( const item of inputSequence ) {
21+ if ( ! seen . has ( item ) ) {
22+ seen . add ( item ) ;
23+ uniqueItems . push ( item ) ;
3224 }
3325 }
3426
You can’t perform that action at this time.
0 commit comments