Remove Nth Node From End of List
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
Follow up: Could you do this in one pass?
Approach1: Two Pass
In this approach, we do a first pass over the Linked List to obtain it's length. With this newfound length we are able to have our pointer situated before the Nth node from the end of the list by substracting the Nth Node from the total length length = length - n. From there, we would simply move a pointer to that postion and remove the Nth Node from End of List.
Time: O(n) Space: O(1)
Approach2: One Pass (optimal)
We will effectuate a one-pass solution using two pointers.
Move one pointer
fast
--> n
steps forward in order to maintain a distance ofn
between the two pointersOnce
fast
pointer is n steps forward, concurrently move both pointers forward until fast reaches the end of the list since it was already in advance.When fast pointer reaches end of list,
n
will be at the position right before thenth
node which is ideal since we want ot remove thenth
Nod
Time: O(n) Space: O(1)
Java Version (optimal)
Last updated
Was this helpful?