1
# Runtime: 784 ms (Top 40.9%) | Memory: 50.79 MB (Top 42.2%)
2

3

4
class Solution:
5
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
6
tot = 0 # initialise total
7
Head = head
8
while Head: # count total nodes
9
Head = Head.next # move forward
10
tot += 1 # incerse count by one for each node
11
one, two = None, None # two pointers of one and two
12
count = (
13
1 # we're initialising to one because we have one based index for swapping
14
)
15
Head = head # regain original head to traverse
16
while Head:
17
if one and two:
18
break # if we have both one and two then break loop to save time
19
if (
20
count == k
21
): # if from forward we reach at node k then it's our first node
22
one = Head
23
if count == (
24
tot - k + 1
25
): # if from backward we reach to node k then save it
26
two = Head
27
Head = Head.next # move further
28
count += 1 # increse count
29
one.val, two.val = two.val, one.val # now swap values
30
return head # return head

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0