Problem 246701 · easy · Level 02 Linear Data Structures

The Song k Tracks Before the End

linked list · two pointers

Tonight's radio playlist is a singly linked list of track numbers. The presenter wants to trail one song in advance: the one that is k-th from the end of the list, where k = 1 is the very last track. Given the head and k, return that track's value, or None if k is below 1 or longer than the playlist.

Examples

Input:  head = 6 -> 2 -> 8 -> 5 -> 1, k = 2
Output: 5

Input:  head = 7 -> 4 -> 9, k = 3
Output: 7

Constraints

  • 0 <= number of nodes <= 10**4
  • -10**4 <= k <= 10**4
  • Target: O(n) time, O(1) extra space, in one pass (no counting pass first)

Goals

  • Use two pointers separated by a fixed gap
  • Answer a from-the-end question in a single pass
Starting Python…