61. Rotate List 🔄
Difficulty: Medium - Tags: Linked List
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:
If
kis larger than the length of the list, rotatingktimes is equivalent to rotatingk % ntimes (nbeing the length of the list).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
Edge Cases:
If the list is empty or has only one node, or if
k == 0, return the original list.
Length Calculation:
Traverse the list to find its length and connect the tail to the head to form a circular list.
Determine the New Head:
Use modulo to find the effective rotations needed, reducing unnecessary cycles.
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?