61. Rotate List ๐
Last updated
Last updated
Difficulty: Medium
- Tags: Linked List
Given the head of a linked list, rotate the list to the right by k
places.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
The number of nodes in the list is in the range [0, 500]
.
-100 <= Node.val <= 100
.
0 <= k <= 2 * 10โน
.
To solve this problem, note the following:
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).
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.
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.
O(n): The list is traversed twice (once to calculate the length and once to find the new tail).
O(1): The solution uses constant extra space.
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.