Given the head of a linked list, rotate the list to the right by k places.
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]
Constraints:
[0, 500].-100 <= Node.val <= 1000 <= k <= 2 * 109When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a train made of connected passenger cars that needs to be shifted so that the back cars move to the front. The brute force approach achieves this by repeatedly detaching just the very last car and moving it to the front one car at a time.
Here's how the algorithm would work step-by-step:
def rotate_right(head_node, rotation_count):
if not head_node or not head_node.next or rotation_count == 0:
return head_node
# We must calculate total length first to avoid redundant cycles during rotation
train_length = 1
current_node = head_node
while current_node.next:
train_length += 1
current_node = current_node.next
effective_rotations = rotation_count % train_length
if effective_rotations == 0:
return head_node
# Shift the tail to the front one step at a time until all rotations are done
for rotation_step in range(effective_rotations):
previous_node = None
current_node = head_node
while current_node.next:
previous_node = current_node
current_node = current_node.next
previous_node.next = None
current_node.next = head_node
head_node = current_node
return head_nodeInstead of shifting items one by one, we can connect the ends of our chain into a loop and take a shortcut to find the exact new starting point. This clever trick lets us rearrange the entire sequence in a single smooth pass without wasting any time.
Here's how the algorithm would work step-by-step:
class Solution:
def rotateRight(self, head, rotation_amount):
if not head or not head.next or rotation_amount == 0:
return head
# We determine the exact length and tail node to enable circular linking.
list_length = 1
current_node = head
while current_node.next:
list_length += 1
current_node = current_node.next
current_node.next = head
# We reduce redundant full rotations to avoid unnecessary traversal steps.
effective_rotation = rotation_amount % list_length
steps_to_new_tail = list_length - effective_rotation
new_tail_node = head
for _ in range(steps_to_new_tail - 1):
new_tail_node = new_tail_node.next
# We break the circle at the new boundary to form the final rotated list.
new_head_node = new_tail_node.next
new_tail_node.next = None
return new_head_node| Case | How to Handle |
|---|---|
| head is null or empty list | Return null immediately as there's nothing to rotate. |
| List contains only one node | Return the head as is, since rotating a single-node list doesn't change it. |
| k is zero | Return the original head, as no rotation is needed. |
| k is a large number much greater than the list length | Calculate k % length to find the effective number of rotations to prevent unnecessary looping and potential integer overflow. |
| k is equal to the length of the list | Return the original head, as rotating by the list length results in the original list. |
| List contains a large number of nodes | The solution should iterate through the list only once to find the length and tail, and another time to find the new tail, ensuring linear time complexity O(n). |
| Negative k value | Convert k to its positive equivalent for proper rotation (k = length + (k % length)) to handle negative rotations. |
| Integer overflow when calculating length or k % length | Use appropriate data types (e.g., long) to prevent integer overflow when calculating the length of the linked list or performing modulo operations with large k values. |