November 18, 2024
I was able to reduce this time complexity from O(n) = 2n to O(n) = n by using a list for the elements to be reversed, and then only modifying those rather than stepping through all nodes while reversing.
1# Definition for singly-linked list.2# class ListNode:3# def __init__(self, val=0, next=None):4# self.val = val5# self.next = next6class Solution:7 def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:8 first = head9 start = None10 end = None11 last = None12 toReverse = []13 i = 014 while i < right:15 if i == max(left - 2, 0):16 start = head17 if i == right - 1:18 end = head19 if i >= left - 1 and i < right - 1:20 toReverse.append(head)21 head = head.next22 i += 12324 last = end.next25 if left > 1:26 start.next = end27 start = start.next28 else:29 start = end30 first = start31 head = start32 while toReverse:33 head.next = toReverse.pop()34 head = head.next35 if head.next:36 head.next = last3738 return first
LeetCode 138. Copy List with Random Pointer
LeetCode 25. Reverse Nodes in k-Group