Skip to content

Commit 92faf65

Browse files
committed
Add remove-nth-node-from-end-of-list solution
1 parent eb55547 commit 92faf65

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// 🚀 Optimized Approach: Two-Pointer Method (One-Pass)
2+
// ✅ Time Complexity: O(N), where N is the number of nodes
3+
// ✅ Space Complexity: O(1)
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* function ListNode(val, next) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.next = (next===undefined ? null : next)
10+
* }
11+
*/
12+
/**
13+
* @param {ListNode} head
14+
* @param {number} n
15+
* @return {ListNode}
16+
*/
17+
var removeNthFromEnd = function (head, n) {
18+
let dummy = new ListNode(0, head);
19+
let fast = dummy;
20+
let slow = dummy;
21+
22+
for (let i = 0; i <= n; i++) {
23+
fast = fast.next;
24+
}
25+
26+
while (fast) {
27+
fast = fast.next;
28+
slow = slow.next;
29+
}
30+
31+
slow.next = slow.next.next;
32+
33+
return dummy.next;
34+
};
35+
36+
// ✅ Time Complexity: O(N), where N is the number of nodes
37+
// ✅ Space Complexity: O(1)
38+
39+
/**
40+
* Definition for singly-linked list.
41+
* function ListNode(val, next) {
42+
* this.val = (val===undefined ? 0 : val)
43+
* this.next = (next===undefined ? null : next)
44+
* }
45+
*/
46+
/**
47+
* @param {ListNode} head
48+
* @param {number} n
49+
* @return {ListNode}
50+
*/
51+
// var removeNthFromEnd = function (head, n) {
52+
// let length = 0;
53+
54+
// let node = head;
55+
56+
// // Compute the length of the linked list
57+
// while (node) {
58+
// length += 1;
59+
// node = node.next;
60+
// }
61+
62+
// // Create a dummy node pointing to head (helps handle edge cases)
63+
// let dummy = new ListNode(0, head);
64+
// node = dummy;
65+
66+
// // Move to the node just before the one to be removed
67+
// for (let i = 0; i < length - n; i++) {
68+
// node = node.next;
69+
// }
70+
71+
// // Remove the nth node from the end by updating the next pointer
72+
// node.next = node.next.next;
73+
74+
// // Return the modified linked list (excluding the dummy node)
75+
// return dummy.next;
76+
// };

0 commit comments

Comments
 (0)