Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
klastandlast, both pointing to the headMove the
lastpointer k steps aheadMove both pointers simultaneously until
lastreaches the endReturn the value of
klastpointer
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.
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.
