Two Solutions ( 1 for awesome time and 1 for awesome space)

First Solution for awesome space:

        # Handling the corner case
        root = head
        if root == None or root.next == None:
            return root
        
        # Calculating the number of nodes
        length = 0
        while root:
            root = root.next
            length += 1
        
        # Calculating the correct k considering circular shifts
        k = k % length
        # Return the head if k is 0 (no shift)
        if k == 0:
            return head
        
        # Reseting the root
        root = head
        counter = 0
        # Finding the new last node and the new head
        while counter < length - k - 1:
            root = root.next
            counter += 1
        last_element = root
        new_head = last_element.next
        
        # Finding the middle conjunction (e.g., [1,2,3,4,5,6] with shift 2 -> finding 6)
        while root.next:
            root = root.next
        middle_element = root
        
        # Correcting the next elements
        last_element.next = None
        middle_element.next = head
        
        return new_head

Second solution for awesome time:

        # Creating a list to store the ndoes
		nodes = []
		# Appending the nodes
        while root:
            nodes.append(root)
            root = root.next
        
		# Calculating the new k considering circulars
        k = k % len(nodes)
        # if k is 0 return the head itself
        if k == 0:
            return head
        
        # Chopping off the sublists according to shift (e.g., [1,2,3,4,5,6] with k = 2 -> [1,2,3,4] and [5,6]
        second_part = nodes[len(nodes)-k:]
        first_part = nodes[:len(nodes)-k]
        
		# Correcting the next elements
        second_part[-1].next = None
        first_part[-1].next = None    
        second_part[-1].next = first_part[0]
		
		# Returning the new head
        return second_part[0]
Comments (0)