Problem
Given the head of a linked list, rotate the list to the right by k places.
Examples
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]
Solution
Method 1 - Iterative
Let’s take the linked list [1, 2, 3, 4, 5]
as an example:
- Determine Length: First, calculate the length of the linked list (
n
). In this case,n = 5
. - Calculate Effective Rotations: Compute
k % n
to find the effective number of rotations needed. For instance, ifk = 2
, then2 % 5 = 2
. - Traverse and Split: Traverse the list to the
(n - k)
th node and split the list into two parts. Fork = 2
, this means traversing(5 - 2) = 3
nodes, resulting inpart1 = [1, 2, 3]
andpart2 = [4, 5]
. - Reassemble the List: Concatenate the second part (
part2
) at the beginning of the first part (part1
). The list now becomes[4, 5, 1, 2, 3]
.
Code
Java
public ListNode rotateRight(ListNode head, int k) {
//for empty or list with 1 node return them as such
if(head == null || head.next == null || k == 0)
return head;
ListNode p = head;
//length starts from 1 to include last element
int len = 1; // note we are not setting to 0, but
// as we want pointer to last element
while(p.next!=null){
p = p.next;
len++;
}
k = k % len;
if (k == 0){
return head;
}
ListNode end = p;
p = head;
for(int i = 0;i<len-k-1;i++){
p = p.next;
}
ListNode newHead = p.next;
p.next = null;
end.next = head;
return newHead;
}
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)
Method 2 - Make a Cycle OR Circular Linkedlist
Same as previous solution, but we can make a cycle. Let’s take the linked list [1, 2, 3, 4, 5]
as an example:
- Determine Length: Calculate the length of the linked list (
n
). In this case,n = 5
. - Create a Cycle: Connect the last node to the head to form a circular linked list.
- Calculate Effective Rotations: Compute
k % n
to determine the effective number of rotations needed. For example, ifk = 2
, then2 % 5 = 2
. - Traverse and Split: Traverse the list from the head to the
(n - k)
th node, then split the list. Fork = 2
, this means traversing(5 - 2) = 3
nodes, resulting in list:[4, 5, 1, 2, 3]
- Make second part as first part: Make second part first, and first part second
Code
Java
public ListNode rotateRight(ListNode head, int k) {
if(head == null || k == 0) {
return head;
}
ListNode p = head;
int len = 1;
while(p.next != null) {
p = p.next;
len++;
}
p.next = head;// make it a circle here
k %= len;
for(int i = 0; i < len - k; i++) {
p = p.next;
}
head = p.next;
p.next = null;
return head;
}
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)