Find the Kth Node From the End of a Linked List

Implement kthNodeFromEnd

Given the head of a singly linked list and an integer k, return the value of the kth node counted from the end of the list (1-indexed, so k = 1 is the last node). Return -1 if k is larger than the list. A singly linked list can only be walked forward, so "distance from the end" isn't something a single pointer knows on its own. The optimal solution fixes that with a head startHead Start (k-Gap) TechniqueAdvance one pointer k steps before starting the second one. The k-node gap between them stays constant as both move together, so when the leading pointer runs out of list, the trailing pointer is exactly k nodes from the end.: let fast move k steps ahead of slow, then walk both together — the fixed gap between them means slow lands exactly on the answer the moment fast falls off the end.

Example 1:

Input: head = [2,4,6,8,10], k = 2

Output: 8

Example 2:

Input: head = [1,2,3], k = 1

Output: 3

Example 3:

Input: head = [1,2,3], k = 5

Output: -1

+ 5 hidden test cases run on Submit.

Constraints:

  • 1 ≤ number of nodes in head ≤ 10⁴
  • -10⁹ ≤ node value ≤ 10⁹
  • k is 1-indexed from the end — k = 1 means the last node
  • If k is greater than the number of nodes, return -1

head =

[2, 4, 6, 8, 10]

k =

2