Skip to content

Commit 12ed6eb

Browse files
committed
Added removeNthFromEnd solution
1 parent cc30fce commit 12ed6eb

File tree

1 file changed

+33
-0
lines changed

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+
var removeNthFromEnd = function (head, n) {
2+
// Edge case: If the list is empty
3+
if (!head) return null;
4+
5+
// Create a dummy node that points to the head
6+
let dummy = new ListNode(0);
7+
dummy.next = head;
8+
let length = 0,
9+
curr = head;
10+
11+
// Calculate the length of the list
12+
while (curr) {
13+
length++;
14+
curr = curr.next;
15+
}
16+
17+
// Find the length-n node from the beginning
18+
length = length - n;
19+
curr = dummy;
20+
while (length > 0) {
21+
length--;
22+
curr = curr.next;
23+
}
24+
25+
// Skip the desired node
26+
curr.next = curr.next.next;
27+
28+
// Return the head, which may be a new head if we removed the first node
29+
return dummy.next;
30+
};
31+
32+
// TC: O(n)
33+
// SC: O(1)

0 commit comments

Comments
 (0)