[
linked list
]
BinarySearch 0994 Swap Kth Node Values
Problem statement
https://binarysearch.com/problems/Swap-Kth-Node-Values/
Solution
Equal to Leetcode 1721. Swapping Nodes in a Linked List.
Complexity
Time complexity is O(n)
, more specifially we did n + n - k = 2n-k
steps when we traverse our list. Space complexity is O(1)
.
Code
class Solution:
def solve(self, head, k):
n = 0
beg = head
while beg:
if n == k: l = beg
beg = beg.next
n += 1
r = head
for m in range(n-k-1):
r = r.next
l.val, r.val = r.val, l.val
return head