61. Rotate List 🔄

Difficulty: Medium - Tags: Linked List

LeetCode Problem Link


Problem Statement 📜

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


Examples 🌟

🔹 Example 1:

Input:

Output:


🔹 Example 2:

Input:

Output:


Constraints ⚙️

  • The number of nodes in the list is in the range [0, 500].

  • -100 <= Node.val <= 100.

  • 0 <= k <= 2 * 10⁹.


Solution 💡

To solve this problem, note the following:

  1. If k is larger than the length of the list, rotating k times is equivalent to rotating k % n times (n being the length of the list).

  2. The rotation can be achieved by:

    • Connecting the tail to the head to form a circular linked list.

    • Breaking the circle at the new head position.


Java Solution


Explanation of the Solution

  1. Edge Cases:

    • If the list is empty or has only one node, or if k == 0, return the original list.

  2. Length Calculation:

    • Traverse the list to find its length and connect the tail to the head to form a circular list.

  3. Determine the New Head:

    • Use modulo to find the effective rotations needed, reducing unnecessary cycles.

  4. Break the Circle:

    • Traverse the list to the new tail and disconnect it from the rest, defining the new head.


Time Complexity ⏳

  • O(n): The list is traversed twice (once to calculate the length and once to find the new tail).

Space Complexity 💾

  • O(1): The solution uses constant extra space.


Follow-up 🧐

This solution is efficient and handles edge cases well. It avoids unnecessary rotations by optimizing k and uses in-place manipulation to save space.

You can find the full solution here.

Last updated

Was this helpful?