Skip to content

Commit f42bd6e

Browse files
committed
Add week 7 solutions : removeNthNodeFromEndOfList
1 parent c0da1e6 commit f42bd6e

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(1)
3+
4+
var removeNthFromEnd = function (head, n) {
5+
// calculate the length of the linked list.
6+
let length = 0;
7+
let current = head;
8+
while (current !== null) {
9+
length++;
10+
current = current.next;
11+
}
12+
13+
// determine the position to remove from the start.
14+
let removeIndex = length - n;
15+
16+
// if the node to be removed is the head, return the next node.
17+
if (removeIndex === 0) {
18+
return head.next;
19+
}
20+
21+
// traverse to the node just before the node to be removed.
22+
current = head;
23+
for (let i = 0; i < removeIndex - 1; i++) {
24+
current = current.next;
25+
}
26+
27+
// remove the nth node from the end.
28+
current.next = current.next.next;
29+
30+
// return the modified list.
31+
return head;
32+
};

0 commit comments

Comments
 (0)