Program to find the K-th last node of a linked list in Python

Suppose we have a singly linked list, we have to find the value of the k-th last node (0-indexed) in a single pass. This is a classic two-pointer technique problem.

So, if the input is like node = [5,4,6,3,4,7], k = 2, then the output will be 3, as the second last (index 3) node has the value of 3.

Algorithm

To solve this, we will follow these steps −

  • Initialize two pointers: klast and last, both pointing to the head

  • Move the last pointer k steps ahead

  • Move both pointers simultaneously until last reaches the end

  • Return the value of klast pointer

How It Works

The key insight is maintaining a gap of k nodes between the two pointers. When the last pointer reaches the end, the klast pointer will be at the k-th last node.

Two-Pointer Technique for K-th Last Node 5 4 6 3 4 7 klast last K-th last node (k=2) Gap of k=2 nodes between pointers

Implementation

class ListNode:
    def __init__(self, data, next=None):
        self.val = data
        self.next = next

def make_list(elements):
    head = ListNode(elements[0])
    for element in elements[1:]:
        ptr = head
        while ptr.next:
            ptr = ptr.next
        ptr.next = ListNode(element)
    return head

class Solution:
    def solve(self, node, k):
        klast = node
        last = node
        
        # Move last pointer k steps ahead
        for i in range(k):
            last = last.next
        
        # Move both pointers until last reaches end
        while last.next:
            last = last.next
            klast = klast.next
        
        return klast.val

# Test the solution
ob = Solution()
linked_list = make_list([5, 4, 6, 3, 4, 7])
result = ob.solve(linked_list, 2)
print(f"The 2nd last node value is: {result}")
The 2nd last node value is: 3

Time and Space Complexity

  • Time Complexity: O(n) where n is the number of nodes

  • Space Complexity: O(1) as we only use two pointers

Conclusion

The two-pointer technique efficiently finds the k-th last node in a single pass. By maintaining a gap of k nodes between pointers, we can locate the target node when the leading pointer reaches the end.

Updated on: 2026-03-25T11:13:42+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements