Solution 1

  • TimeO(n)
  • SpaceO(1)

where, n is the total number of nodes
NOTE: This is best possible solution in terms of time and space complexity,
But, since you used pointers, you took a lot of time to implement it, around 43 min (including the dry run for your understanding), good news is you've done it all by yourself, you could have implemented it much more quicker if you had used a stack/list approach, implementing pointers for complex problems, especially when you have to dry run the code is time consuming

Python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    '''
    Time Complexity: O(n)
    Space Complexity: O(1)
    where, n is the total number of nodes
    NOTE: This is best possible solution in terms of time and space complexity,
    But, since you used pointers, you took a lot of time to implement it, 
    around 43 min (including the dry run for your understanding), 
    good news is you've done it all by yourself, 
    you could have implemented it much more quicker if you had used a stack/list approach,
    implementing pointers for complex problems, especially when you have to dry run the code is time consuming
    '''
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        dummy = ListNode(0)
        dummy.next = head
        leftLimit, cur, old, rightLimit = dummy, head, dummy, dummy
        while True:
            for _ in range(k):
                if rightLimit:
                    rightLimit = rightLimit.next
                else:
                    break
            
            if not rightLimit:
                break
            
            end = rightLimit
            rightLimit = rightLimit.next

            while old != end:
                temp = cur.next
                cur.next = old
                old = cur
                cur = temp
            
            start = leftLimit.next
            leftLimit.next = end
            start.next = rightLimit
            
            leftLimit, cur, old, rightLimit = start, rightLimit, start, start
        
        return dummy.next
Leet Code/python.py · L1468–1515