Taro Logo

Rotate List

#14 Most AskedMedium
Topics:
Linked Lists

Given the head of a linked list, rotate the list to the right by k places.

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

Example 2:

Input: head = [0,1,2], k = 4
Output: [2,0,1]

Constraints:

  • The number of nodes in the list is in the range [0, 500].
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can `k` be larger than the total number of nodes in the linked list, and if so, how should we handle it?
  2. What should be returned if the input linked list is empty (`head` is null) or contains only a single node?
  3. Can `k` be negative, or is it guaranteed to be a non-negative integer?
  4. Should the rotation be performed in-place by modifying the existing pointers, or are we allowed to use extra space to construct a new list?
  5. If `k` is a multiple of the length of the linked list (meaning the list remains unchanged after rotation), should I return the original list as-is?

Brute Force Solution

Approach

Imagine you have a train made of connected passenger cars that needs to be shifted so that the back cars move to the front. The brute force approach achieves this by repeatedly detaching just the very last car and moving it to the front one car at a time.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire train of connected cars from the front to the back.
  2. Find the very last car in the train and the car right before it.
  3. Detach the last car from the rest of the train.
  4. Move that detached car to the absolute front of the train and connect it so it becomes the new leader.
  5. Repeat this entire process of detaching the end car and placing it at the front as many times as the rotation amount requires.

Code Implementation

def rotate_right(head_node, rotation_count):
    if not head_node or not head_node.next or rotation_count == 0:
        return head_node

    # We must calculate total length first to avoid redundant cycles during rotation
    train_length = 1
    current_node = head_node
    while current_node.next:
        train_length += 1
        current_node = current_node.next

    effective_rotations = rotation_count % train_length
    if effective_rotations == 0:
        return head_node

    # Shift the tail to the front one step at a time until all rotations are done
    for rotation_step in range(effective_rotations):
        previous_node = None
        current_node = head_node

        while current_node.next:
            previous_node = current_node
            current_node = current_node.next

        previous_node.next = None
        current_node.next = head_node
        head_node = current_node

    return head_node

Big(O) Analysis

Time Complexity
O(n * k) – In this brute force approach, we repeat the process of detaching the last car and moving it to the front k times. For each of the k rotations, we must traverse the entire linked list of size n to find the last car and the one right before it. This means we perform n operations during each of the k iterations. Combining these steps leads to approximately k * n total operations, which simplifies to O(n * k).
Space Complexity
O(1) – The brute force approach described relies entirely on manipulating the existing pointers of the connected cars without allocating any new auxiliary data structures. We only use a fixed number of pointer and counter variables to keep track of the last car, the second-to-last car, and the number of repetitions. Because these variables occupy a constant amount of memory regardless of how many cars are in the train, the extra space required remains completely independent of the input size N. Therefore, the auxiliary space complexity is constant.

Optimal Solution

Approach

Instead of shifting items one by one, we can connect the ends of our chain into a loop and take a shortcut to find the exact new starting point. This clever trick lets us rearrange the entire sequence in a single smooth pass without wasting any time.

Here's how the algorithm would work step-by-step:

  1. Count the total number of items in the chain to understand its exact length.
  2. Connect the very last item directly to the very first item, turning the chain into a complete circle.
  3. Figure out that if we shift the chain by a number equal to the total count, we end up right back where we started.
  4. Simplify the requested shift amount by ignoring full circles, leaving only the leftover steps we actually need to move.
  5. Walk forward along the circular chain by that exact leftover amount to find the spot where the new beginning should be.
  6. Disconnect the circle right before that new beginning to form a fresh, properly rotated chain.

Code Implementation

class Solution:
    def rotateRight(self, head, rotation_amount):
        if not head or not head.next or rotation_amount == 0:
            return head

        # We determine the exact length and tail node to enable circular linking.
        list_length = 1
        current_node = head
        while current_node.next:
            list_length += 1
            current_node = current_node.next

        current_node.next = head

        # We reduce redundant full rotations to avoid unnecessary traversal steps.
        effective_rotation = rotation_amount % list_length
        steps_to_new_tail = list_length - effective_rotation

        new_tail_node = head
        for _ in range(steps_to_new_tail - 1):
            new_tail_node = new_tail_node.next

        # We break the circle at the new boundary to form the final rotated list.
        new_head_node = new_tail_node.next
        new_tail_node.next = None

        return new_head_node

Big(O) Analysis

Time Complexity
O(n) – First, we traverse the entire linked list of length n to count its total items and find the tail. Next, we walk forward from the head by the simplified leftover shift amount, which takes at most n steps. Since these two sequential passes each scale linearly with the number of nodes, the total operations approximate n + n. Dropping the constant factor gives a final time complexity of O(n).
Space Complexity
O(1) – The algorithm only uses a few pointers to track the tail, head, and new breaking point, along with an integer variable to store the length of the list. No additional data structures, auxiliary arrays, or recursive call stacks are created during the process. Therefore, the extra memory required remains constant regardless of the input list size N.

Edge Cases

head is null or empty list
How to Handle:
Return null immediately as there's nothing to rotate.
List contains only one node
How to Handle:
Return the head as is, since rotating a single-node list doesn't change it.
k is zero
How to Handle:
Return the original head, as no rotation is needed.
k is a large number much greater than the list length
How to Handle:
Calculate k % length to find the effective number of rotations to prevent unnecessary looping and potential integer overflow.
k is equal to the length of the list
How to Handle:
Return the original head, as rotating by the list length results in the original list.
List contains a large number of nodes
How to Handle:
The solution should iterate through the list only once to find the length and tail, and another time to find the new tail, ensuring linear time complexity O(n).
Negative k value
How to Handle:
Convert k to its positive equivalent for proper rotation (k = length + (k % length)) to handle negative rotations.
Integer overflow when calculating length or k % length
How to Handle:
Use appropriate data types (e.g., long) to prevent integer overflow when calculating the length of the linked list or performing modulo operations with large k values.
0/33 completed