File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {ListNode } head
3
+ * @param {number } n
4
+ * @return {ListNode }
5
+ */
6
+ function removeNthFromEnd ( head , n ) {
7
+ let dummy = new ListNode ( 0 ) ;
8
+ dummy . next = head ;
9
+ let first = dummy ;
10
+ let second = dummy ;
11
+
12
+ // Move the first pointer n+1 steps ahead
13
+ for ( let i = 0 ; i <= n ; i ++ ) {
14
+ first = first . next ;
15
+ }
16
+
17
+ // Move both pointers until the first pointer reaches the end
18
+ // Second pointer will be at the (n+1)th node from the end
19
+ while ( first !== null ) {
20
+ first = first . next ;
21
+ second = second . next ;
22
+ }
23
+
24
+ // Remove the nth node from the end
25
+ second . next = second . next . next ;
26
+
27
+ return dummy . next ;
28
+ }
29
+
30
+ /**
31
+ * Time Complexity: O(n)
32
+ * Space Complexity: O(1)
33
+ */
You can’t perform that action at this time.
0 commit comments