19. Remove Nth Node From End of List


Remove Nth Node From End of List

Remove Nth Node From End of List

Problem Description

Given the head of a linked list, remove the nth node from the end of the list and return its head.

 

Example 1:

Linked List


Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]


Example 2:

Input: head = [1], n = 1
Output: []


Example 3:

Input: head = [1,2], n = 1
Output: [1]

 

Constraints:

  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

 

Follow up: Could you do this in one pass?


Let`s code it!

var removeNthFromEnd = function(head, n) {
    let tempList = new ListNode(0);
    tempList.next = head;
	
    // set variables for next node and current node
    let slow = tempList;
    let fast = tempList;
	
    // set fast to n nodes ahead of slow
    for (let i = 0; i <= n; i++) {
        fast = fast.next;
    }
	
    // While we haven't reached the end of the list
    // set slow to n nodes behind fast
    while (fast) {
        slow = slow.next;
        fast = fast.next;
    }
	
    // set slow.next to two nodes ahead of slow
    // then return the nth node of the list
    slow.next = slow.next.next;
    return tempList.next;
}
Time complexity is 0(n)
Space complexity 0(1)
Runtime: 60 ms, faster than 95.08% of JavaScript online submissions for Remove Nth Node From End of List.
Memory Usage: 42.7 MB, less than 72.68% of JavaScript online submissions for Remove Nth Node From End of List.


Conclusion

That’s all folks! In this post, we solved LeetCode problem #19. Remove Nth Node From End of List

I hope you have enjoyed this post. Feel free to share your thoughts on this.

You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.


In this blog, I have tried to collect & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!

Comments

Popular Post