Skip to content

Rotate List

Given the head of a linked list, rotate the list to the right by k places.

Rotating a list to the right by k places means taking the last k nodes and moving them to the front of the list, preserving their relative order.

InputkOutputExplanation
1 → 2 → 3 → 4 → 524 → 5 → 1 → 2 → 3Move the last 2 nodes to the front
0 → 1 → 242 → 0 → 1k % length = 4 % 3 = 1, rotate by 1
111Single node; rotation has no effect
1 → 221 → 2Full rotation by list length; no change
  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100
  • 0 <= k <= 2 * 10^9
ApproachTimeSpacePassesBest When
Break PointO(n)O(1)2Easier to understand the concept; clear two-phase algorithm
CircularO(n)O(1)1Want a more elegant single-pass-like approach; showing pattern mastery
  • Pick Break Point if you are learning linked list manipulation for the first time.
  • Pick Circular if you want to see an elegant alternative using the cyclic nature of the problem.
Conceptually Clear
Break Point
O(n) time · O(1) space
Elegant Alternative
Circular
O(n) time · O(1) space
★ Recommended

Find the node at position (length - k - 1) and break the list there. The new head is the node that follows this break point. Reconnect the tail of the rotated portion to the original head.

The key insight is understanding that after a right rotation by k, the node that was at position length - k becomes the new head.

⏱ Time O(n) Two passes 💾 Space O(1)

Input: 1 → 2 → 3 → 4 → 5, k = 2

Step 1: Find length = 5

Step 2: Normalize k = 2 (already less than 5)

Step 3: Find break point at position 5 - 2 - 1 = 2 (the node with value 3)

Step 4: Break the list:

  • Separate: 1 → 2 → 3 (break here) and 4 → 5
  • Set 3.next = null
  • Connect the tail of 4 → 5 (which is 5) back to 1
  • Result: 4 → 5 → 1 → 2 → 3

Another case: 0 → 1 → 2, k = 4

Step 1: Find length = 3

Step 2: Normalize k = 4 % 3 = 1

Step 3: Find break point at position 3 - 1 - 1 = 1 (the node with value 1)

Step 4: Break and reconnect:

  • 0 → 1 and 2
  • 2.next points to 0
  • Result: 2 → 0 → 1
function rotateListBreakPoint(head, k):
if head is null or head.next is null or k == 0:
return head
// Step 1: Find length
length = 0
current = head
while current != null:
length++
current = current.next
// Step 2: Normalize k
k = k % length
if k == 0:
return head
// Step 3: Find break point
current = head
for i from 0 to length - k - 2:
current = current.next
// Step 4: Break and reconnect
newHead = current.next
current.next = null
tail = newHead
while tail.next != null:
tail = tail.next
tail.next = head
return newHead
rotate_list_break_point.py
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def rotate_list_break_point(head: Optional[ListNode], k: int) -> Optional[ListNode]:
"""
Rotate a linked list to the right by k positions using the break point approach.
Approach:
1. Calculate the effective rotation: k = k % length
2. Find the break point: the node at position (length - k - 1)
3. Perform rotation by breaking the list at the break point
Time: O(n) - single pass to find length, single pass to find break point
Space: O(1) - only using pointers
"""
if not head or not head.next or k == 0:
return head
# Step 1: Find the length of the list
length = 0
current = head
while current:
length += 1
current = current.next
# Step 2: Normalize k (handle cases where k > length)
k = k % length
if k == 0:
return head
# Step 3: Find the break point (node before rotation point)
# We need to find the (length - k - 1)th node
current = head
for i in range(length - k - 1):
current = current.next
# Step 4: Perform rotation
# The new head is current.next
new_head = current.next
current.next = None
# Find the tail of the new list and connect it back to the old head
tail = new_head
while tail.next:
tail = tail.next
tail.next = head
return new_head
# Helper function to create a linked list from a list
def create_linked_list(values):
if not values:
return None
head = ListNode(values[0])
current = head
for val in values[1:]:
current.next = ListNode(val)
current = current.next
return head
# Helper function to convert linked list to list for easy printing
def linked_list_to_list(head):
result = []
current = head
while current:
result.append(current.val)
current = current.next
return result
# Test cases
if __name__ == "__main__":
# Test 1: [1, 2, 3, 4, 5], k=2
head1 = create_linked_list([1, 2, 3, 4, 5])
result1 = rotate_list_break_point(head1, 2)
print(linked_list_to_list(result1)) # [4, 5, 1, 2, 3]
# Test 2: [0, 1, 2], k=4
head2 = create_linked_list([0, 1, 2])
result2 = rotate_list_break_point(head2, 4)
print(linked_list_to_list(result2)) # [2, 0, 1]
# Test 3: [1], k=1
head3 = create_linked_list([1])
result3 = rotate_list_break_point(head3, 1)
print(linked_list_to_list(result3)) # [1]
# Test 4: [1, 2], k=2
head4 = create_linked_list([1, 2])
result4 = rotate_list_break_point(head4, 2)
print(linked_list_to_list(result4)) # [1, 2]
# Test 5: [1, 2, 3, 4, 5], k=0
head5 = create_linked_list([1, 2, 3, 4, 5])
result5 = rotate_list_break_point(head5, 0)
print(linked_list_to_list(result5)) # [1, 2, 3, 4, 5]
🎯 Interview Favourite

Create a circular list by connecting the tail back to the head, then locate the new head at position (length - k) and break the circle there. This approach elegantly leverages the cyclic nature of rotation.

⏱ Time O(n) Find length and walk to break point 💾 Space O(1)

Input: 1 → 2 → 3 → 4 → 5, k = 2

Step 1: Find length = 5, identify tail (node 5)

Step 2: Normalize k = 2

Step 3: Create circular list: 5.next = 11 → 2 → 3 → 4 → 5 → 1 → 2 → 3 → ...

Step 4: Walk length - k = 5 - 2 = 3 steps from head (starting at position 0):

  • Step 0: at node 1
  • Step 1: at node 2
  • Step 2: at node 3

Step 5: Break after node 3:

  • new_head = 3.next = 4
  • 3.next = null
  • Result: 4 → 5 → 1 → 2 → 3

Another case: 0 → 1 → 2, k = 4

Step 1: Find length = 3, tail = node 2

Step 2: Normalize k = 1

Step 3: Create circular list: 2.next = 0

Step 4: Walk 3 - 1 = 2 steps from head:

  • Step 0: at node 0
  • Step 1: at node 1

Step 5: Break after node 1:

  • new_head = 1.next = 2
  • 1.next = null
  • Result: 2 → 0 → 1
function rotateListCircular(head, k):
if head is null or head.next is null or k == 0:
return head
// Step 1: Find length and tail
length = 0
tail = head
while tail.next != null:
length++
tail = tail.next
length++
// Step 2: Normalize k
k = k % length
if k == 0:
return head
// Step 3: Create circular list
tail.next = head
// Step 4: Find new head position
stepsToWalk = length - k
current = head
for i from 0 to stepsToWalk - 2:
current = current.next
// Step 5: Break the circle
newHead = current.next
current.next = null
return newHead
rotate_list_circular.py
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def rotate_list_circular(head: Optional[ListNode], k: int) -> Optional[ListNode]:
"""
Rotate a linked list to the right by k positions using the circular approach.
Approach:
1. Calculate the effective rotation: k = k % length
2. Create a circular list by connecting the tail to the head
3. Find the new head position: walk (length - k) steps from the original head
4. Break the circle at the appropriate point
Time: O(n) - single pass to find length and establish circle, walk (length - k) steps
Space: O(1) - only using pointers
"""
if not head or not head.next or k == 0:
return head
# Step 1: Find the length of the list and the tail
length = 0
tail = head
while tail.next:
length += 1
tail = tail.next
length += 1 # Add 1 for the tail node itself
# Step 2: Normalize k
k = k % length
if k == 0:
return head
# Step 3: Create a circular list
tail.next = head
# Step 4: Find the new head position
# After rotation by k, the new head is at position (length - k)
# We need to walk (length - k) steps from the original head
steps_to_walk = length - k
current = head
for i in range(steps_to_walk - 1):
current = current.next
# Step 5: Break the circle
new_head = current.next
current.next = None
return new_head
# Helper function to create a linked list from a list
def create_linked_list(values):
if not values:
return None
head = ListNode(values[0])
current = head
for val in values[1:]:
current.next = ListNode(val)
current = current.next
return head
# Helper function to convert linked list to list for easy printing
def linked_list_to_list(head):
result = []
current = head
while current:
result.append(current.val)
current = current.next
return result
# Test cases
if __name__ == "__main__":
# Test 1: [1, 2, 3, 4, 5], k=2
head1 = create_linked_list([1, 2, 3, 4, 5])
result1 = rotate_list_circular(head1, 2)
print(linked_list_to_list(result1)) # [4, 5, 1, 2, 3]
# Test 2: [0, 1, 2], k=4
head2 = create_linked_list([0, 1, 2])
result2 = rotate_list_circular(head2, 4)
print(linked_list_to_list(result2)) # [2, 0, 1]
# Test 3: [1], k=1
head3 = create_linked_list([1])
result3 = rotate_list_circular(head3, 1)
print(linked_list_to_list(result3)) # [1]
# Test 4: [1, 2], k=2
head4 = create_linked_list([1, 2])
result4 = rotate_list_circular(head4, 2)
print(linked_list_to_list(result4)) # [1, 2]
# Test 5: [1, 2, 3, 4, 5], k=0
head5 = create_linked_list([1, 2, 3, 4, 5])
result5 = rotate_list_circular(head5, 0)
print(linked_list_to_list(result5)) # [1, 2, 3, 4, 5]

Animated walkthrough

Understanding rotation: finding the break point and reconnecting

Watch how the algorithm identifies the break point and performs the rotation. The list is broken at position (length - k - 1), then reconnected to create the rotated list.

Step 1 of 4 Target: rotation
Waiting to begin...
Array state
Memory / lookup state

✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
rotate_list_optimized.py
"""
Solution for Rotate List
"""
def solve():
"""Implementation for approach 3 of Rotate List"""
pass
if __name__ == "__main__":
print("Solution ready")