← Questions
Nth node from the end of a linked list
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Aug 2025. It tests linked lists and two pointers.
Given the head of a singly linked list and an integer k, return the k-th node counted from the end (k = 1 is the last node). Do it in one pass over the list.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
kth_from_end(head: ListNode | None, k: int) -> ListNode | None— the nodekplaces from the end, orNonewhenk < 1orkis longer than the list.
Example
list 1 -> 2 -> 3 -> 4 -> 5, k = 2 -> node 4
list 1, k = 1 -> node 1
list 1 -> 2, k = 3 -> None # k is longer than the list
Constraints
-
1 <= number of nodes <= 10^4; values fit in a 32-bit signed integer. -
k >= 1, but it may exceed the length. -
O(1)extra space.
Clarifying questions
- Is
k1-based from the end? - What should happen when
kis larger than the list: returnNone, or raise? - Do I return the node or its value, and may I modify the list?
What a strong answer covers
- Two pointers: move a lead pointer
ksteps ahead, then move both until the lead falls off the end; the trailing pointer is the answer.O(n)time,O(1)space. - Detecting a too-large
kwhile advancing the lead pointer. - Comparison with the two-pass approach (count the length, then walk
n - ksteps) and why one pass matters for a stream. - Tests:
k = 1,kequal to the length,kpast the end, a one-node list.
Follow-ups
- Remove the
k-th node from the end and return the new head; use a dummy node so removing the head needs no special case. - Return the middle node in one pass.
- The list may contain a cycle. How do you detect it first?
Where it's asked
- Meta · AI-enabled coding · Last asked Aug 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
linked lists · two pointers
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
