Min-Hsueh Chiu

Logo

  • Projects
  • Publications
  • Blog
  • CV
  • Random things
  • Theme by orderedlist

    I struggle to grasp vanAmsen's concise O(1) space complexity algorithm. I've utilized the following visualization to analyze each step systematically to comprehend it fully.


    Key Points:

    1. advance the current node to the right by:
     (1) adjusting the current.next pointer
    2. put next_node all the way left to pre.next by
     (2) updating pre.next pointer
     (3) updating next_node.next pointer


    class Solution:
        def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
            if not head or left == right:
                return head
            
            dummy = ListNode(0, head)
            prev = dummy
            
            for _ in range(left - 1):
                prev = prev.next
            
            current = prev.next
            
            for _ in range(right - left):
                next_node = current.next
                current.next, next_node.next, prev.next = next_node.next, prev.next, next_node
    
            return dummy.next