Skip to content

Commit

Permalink
Add week 7 solutions : removeNthNodeFromEndOfList
Browse files Browse the repository at this point in the history
  • Loading branch information
yolophg committed Jun 15, 2024
1 parent c0da1e6 commit f42bd6e
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions remove-nth-node-from-end-of-list/yolophg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Time Complexity: O(n)
// Space Complexity: O(1)

var removeNthFromEnd = function (head, n) {
// calculate the length of the linked list.
let length = 0;
let current = head;
while (current !== null) {
length++;
current = current.next;
}

// determine the position to remove from the start.
let removeIndex = length - n;

// if the node to be removed is the head, return the next node.
if (removeIndex === 0) {
return head.next;
}

// traverse to the node just before the node to be removed.
current = head;
for (let i = 0; i < removeIndex - 1; i++) {
current = current.next;
}

// remove the nth node from the end.
current.next = current.next.next;

// return the modified list.
return head;
};

0 comments on commit f42bd6e

Please sign in to comment.