
Sponsored
Sponsored
This approach involves two passes through the linked list. In the first pass, we determine the kth node from the beginning. In the second pass, we find the kth node from the end. Once we have both nodes, we swap their values. This approach requires a complete traversal of the list during each pass, but is simple to implement.
Time Complexity: O(n) due to two linear passes through the list. Space Complexity: O(1) since we use only pointers.
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6class Solution:
7 def swapNodes(self, head: ListNode, k: int) -> ListNode:
8 length = 0
9 first = head
10 second = head
11 current = head
12
13 while current:
14 length += 1
15 if length == k:
16 first = current
17 current = current.next
18
19 current = head
20 for i in range(length - k):
21 current = current.next
22 second = current
23
24 first.val, second.val = second.val, first.val
25
26 return head
27In Python, we create a ListNode class to define nodes of the list. We use a similar technique by traversing through the linked list twice. In the first pass, we ascertain the kth node from the start and the length of the list. In the second pass, we find the kth node from the end, and then swap values.
This approach optimizes the two-pass technique by using a single traversal with two pointers method. The idea is to leverage two pointers where one pointer reaches the kth node while the other starts marking the start from the head. Once the first pointer reaches the end, the second pointer will be at the correct kth position from the end. We then swap the values directly.
Time Complexity: O(n), as we make only one pass of the list. Space Complexity: O(1).
This Python solution succinctly utilizes the fast and slow pointer technique where fast traverses k steps initially and subsequently the full length thereafter, allowing the slow pointer to point accurately to the desired kth node from the end. The swapping is directly implemented using Python's native value assignment.