File tree Expand file tree Collapse file tree 3 files changed +53
-0
lines changed
Expand file tree Collapse file tree 3 files changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ var mergeTwoLists = function ( list1 , list2 ) {
2+ // create a placeholder node and use it as a starting point
3+ let placeholder = { val : - 1 , next : null } ;
4+ let current = placeholder ;
5+
6+ // loop through the lists until one of them is fully traversed
7+ while ( list1 !== null && list2 !== null ) {
8+ if ( list1 . val <= list2 . val ) {
9+ // connect the element of list1 with the current node
10+ current . next = list1 ;
11+ // move list1 to its next node
12+ list1 = list1 . next ;
13+ } else {
14+ current . next = list2 ;
15+ list2 = list2 . next ;
16+ }
17+ // move the current pointer to the newly added node
18+ current = current . next ;
19+ }
20+ current . next = list1 !== null ? list1 : list2 ;
21+ return placeholder . next ;
22+ } ;
23+
24+ // Time Complexity: O(n+m);
25+ // Space Complexity: O(1)
Original file line number Diff line number Diff line change 1+ var missingNumber = function ( nums ) {
2+ // store all the elemenst from nums in a Set
3+ const set = new Set ( nums ) ;
4+
5+ // check the missing number by iterating through the index
6+ for ( i = 0 ; i <= nums . length ; i ++ ) {
7+ if ( ! set . has ( i ) ) {
8+ return i ;
9+ }
10+ }
11+ } ;
12+
13+ // Time complexity: O(n);
14+ // Space complexity: O(n);
Original file line number Diff line number Diff line change 1+ var twoSum = function ( nums , target ) {
2+ const map = new Map ( ) ;
3+
4+ for ( let i = 0 ; i < nums . length ; i ++ ) {
5+ const complement = target - nums [ i ] ;
6+ if ( map . has ( complement ) ) {
7+ return [ map . get ( complement ) , i ] ;
8+ }
9+ map . set ( nums [ i ] , i ) ;
10+ }
11+ } ;
12+
13+ // Time complexity: O(n)
14+ // Space complexity: O(n) - hash map storage
You can’t perform that action at this time.
0 commit comments