LeetCode: Remove Nth Node From End Of List Solution
Approach
Two pointers here is to maintain the position
Target el is n
dist from tail
fast
and slow
start from head
First, fast
will iterate n
time
- so
fast
isn
dist from head (which is alsoslow
) - aka,
slow
isn
dist fromfast
Then, fast
and slow
will both iterate until fast
reach tail
- because target el is
n
dist from tail - and
slow
isn
dist fromfast
, so the same
Now slow
is pointed to target, remove that
Implementation
1// no fair-play2var removeNthFromEnd = function (head, n) {3 let iter = head4 let arr = []5 while (iter) {6 arr.push(iter.val)7 iter = iter.next8 }9 n = arr.length - n10 arr.splice(n, 1)11 arr = arr.map(el => new ListNode(el))12 for (let i = 0; i < arr.length - 1; i++) {13 arr[i].next = arr[i + 1]14 }15 return arr[0] || null16}1718var removeNthFromEnd = function (head, n) {19 let fast = (slow = head)20 while (n--) {21 fast = fast.next22 }23 if (!fast) {24 return head.next25 }26 while (fast.next) {27 fast = fast.next28 slow = slow.next29 }30 slow.next = slow.next.next31 return head32}
References
Similar problems
Swapping Nodes in a Linked List
Delete N Nodes After M Nodes of a Linked List
Comments
Loading comments...
Tags
leetcode
linked list
two pointers
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.