Taro Logo

Rotate List

Medium
Meta logo
Meta
1 view
Topics:
Linked Lists

Given the head of a singly linked list, rotate the list to the right by k places. Rotating the list means moving the last k elements to the front of the list and shifting the existing elements to the right.

For example:

  • If the list is 1 -> 2 -> 3 -> 4 -> 5 and k = 2, the output should be 4 -> 5 -> 1 -> 2 -> 3.
  • If the list is 0 -> 1 -> 2 and k = 4, the output should be 2 -> 0 -> 1 (since rotating by 4 is the same as rotating by 1 in this case).

Constraints:

  • The number of nodes in the list is in the range [0, 500].
  • Node values can be any integer between -100 and 100.
  • k can be any non-negative integer up to 2 * 10^9.

Write a function that takes the head of a linked list and an integer k, and returns the new head of the rotated list. Explain your approach and consider edge cases such as an empty list or when k is larger than the list size.

Solution


Let's explore how to rotate a linked list to the right by k places.

Naive Approach

The brute force method involves repeatedly moving the last element to the front of the list k times. This is straightforward but inefficient.

  1. For k iterations:
  2. Traverse to the second-to-last node.
  3. Move the last node to the beginning.

This approach modifies the list k times, leading to high time complexity.

  • Time Complexity: O(n*k), where n is the number of nodes in the linked list.
  • Space Complexity: O(1), as it's an in-place algorithm.

This method is highly inefficient for large values of k.

Optimal Approach

A more efficient approach involves these steps:

  1. Calculate the length of the list.
  2. Handle the case where k is larger than the list's length.
    • Use k % length to get the effective rotation value.
  3. Find the new head and tail.
    • Traverse to the (length - k - 1)th node. Its next node will be the new head.
    • The current tail's next pointer should point to the original head.
  4. Set the new tail's next pointer to null.

Edge Cases:

  • If the list is empty or has only one element, or if k is zero, return the original list.
  • If k is a multiple of the list length, no rotation is needed.

Code Example (Java):

public ListNode rotateRight(ListNode head, int k) {
    if (head == null || head.next == null || k == 0) {
        return head;
    }

    ListNode tail = head;
    int length = 1;
    while (tail.next != null) {
        tail = tail.next;
        length++;
    }

    k = k % length;
    if (k == 0) {
        return head;
    }

    ListNode newTail = head;
    for (int i = 1; i < length - k; i++) {
        newTail = newTail.next;
    }

    ListNode newHead = newTail.next;
    newTail.next = null;
    tail.next = head;

    return newHead;
}
  • Time Complexity: O(n), where n is the number of nodes.
  • Space Complexity: O(1), as it's an in-place solution.

This approach minimizes the number of traversals, leading to better performance.