Skip to content

Commit 5e53d5f

Browse files
committed
solve: remove nth node from end of list
1 parent 05d1725 commit 5e53d5f

File tree

1 file changed

+33
-0
lines changed
  • remove-nth-node-from-end-of-list

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
*/

0 commit comments

Comments
 (0)