Problem
Given the head of a linked list, rotate the list to the right by k places.
Examples
Example 1:
|
|
Example 2:
|
|
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
|
|
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
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)