November 23, 2024
I had to read the comments to understand this problem. I didn't understand how they wanted the ordering until I read a few examples.
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 partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:8 start = head9 left, right = None, None1011 while head and not right:12 if head.val < x:13 left = head14 else:15 right = head16 head = head.next1718 prev = None1920 while head:21 if head.val < x:22 if prev:23 prev.next = head.next24 if left:25 left.next = head26 left = left.next27 else:28 left = head29 start = left30 if right.next == head:31 right.next = head.next32 head.next = right3334 prev = head35 head = head.next3637 return start
Time complexity is O(n) = n and space complexity is O(1).
LeetCode 82. Remove Duplicates from Sorted List II
LeetCode 146. LRU Cache