- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 50 lines of Python from the credited upstream file 148.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def sortList(self, head: ListNode) -> ListNode:3 def split(head: ListNode, k: int) -> ListNode:4 while k > 1 and head:5 head = head.next6 k -= 17 rest = head.next if head else None8 if head:9 head.next = None10 return rest11 12 def merge(l1: ListNode, l2: ListNode) -> tuple:13 dummy = ListNode(0)14 tail = dummy15 16 while l1 and l2:17 if l1.val > l2.val:18 l1, l2 = l2, l119 tail.next = l120 l1 = l1.next21 tail = tail.next22 tail.next = l1 if l1 else l223 while tail.next:24 tail = tail.next25 26 return dummy.next, tail27 28 length = 029 curr = head30 while curr:31 length += 132 curr = curr.next33 34 dummy = ListNode(0, head)35 36 k = 137 while k < length:38 curr = dummy.next39 tail = dummy40 while curr:41 l = curr42 r = split(l, k)43 curr = split(r, k)44 mergedHead, mergedTail = merge(l, r)45 tail.next = mergedHead46 tail = mergedTail47 k *= 248 49 return dummy.next50