19. Remove Nth Node From End of List
mediumAsked at GojekRemove the nth node from the end of a singly linked list in one pass.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the head of a linked list, remove the n-th node from the end of the list and return its head.
Constraints
The number of nodes is sz1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz
Examples
Example 1
head = [1,2,3,4,5], n = 2[1,2,3,5]Example 2
head = [1], n = 1[]Approaches
1. Two-pass length
Walk the list once to compute the length, then walk again to the (len - n)-th node and splice.
- Time
- O(L)
- Space
- O(1)
let len = 0; for (let n = head; n; n = n.next) len++;
const dummy = { next: head };
let cur = dummy;
for (let i = 0; i < len - n; i++) cur = cur.next;
cur.next = cur.next.next;
return dummy.next;Tradeoff:
2. Two-pointer gap
Advance a lead pointer n steps ahead, then walk both until lead reaches the end. The trail pointer now sits just before the target.
- Time
- O(L)
- Space
- O(1)
function removeNthFromEnd(head, n) {
const dummy = { next: head };
let lead = dummy, trail = dummy;
for (let i = 0; i < n + 1; i++) lead = lead.next;
while (lead) { lead = lead.next; trail = trail.next; }
trail.next = trail.next.next;
return dummy.next;
}Tradeoff:
Gojek-specific tips
Gojek interviewers reward one-pass solutions because their mobile-first apps fetch over slow SEA networks and re-traversal can mean a visible UI stall.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Remove Nth Node From End of List and other Gojek interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →