Problem statement

https://binarysearch.com/problems/Kth-Last-Node-of-a-Linked-List/

Solution

Almost the same as Leetcode 0019. Remove Nth Node From End of List

Complexity

It is O(n - k) for time and O(1) for space.

Code

class Solution:
    def solve(self, node, k):
        dummy = LLNode(0)
        dummy.next = node
        P1, P2 = dummy, dummy
        for _ in range(k): P2 = P2.next
        
        while P2.next:
            P1 = P1.next
            P2 = P2.next

        return P1.val