#61
Rotate List
MediumLinked ListTwo PointersTwo PointersLinked List Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution involves finding the length of the list and adjusting the pointers to achieve the rotation in a single pass.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the length of the linked list and find the effective rotations needed (k % length).
- 2Step 2: If k is 0, return the head as no rotation is needed.
- 3Step 3: Traverse to the (length - k)th node to find the new tail and set its next to null.
- 4Step 4: Set the next of the new tail to the original head and update the head to the (length - k + 1)th node.
solution.py26 lines
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6def rotateRight(head, k):
7 if not head or not head.next or k == 0:
8 return head
9 n = 0
10 current = head
11 while current:
12 n += 1
13 current = current.next
14 k = k % n
15 if k == 0:
16 return head
17 tail = head
18 for _ in range(n - 1):
19 tail = tail.next
20 tail.next = head
21 new_tail = head
22 for _ in range(n - k - 1):
23 new_tail = new_tail.next
24 head = new_tail.next
25 new_tail.next = None
26 return headℹ
Complexity note: This complexity is O(n) because we traverse the list to find its length and then again to find the new tail. We only use a constant amount of extra space.
- 1Understanding effective rotations (k % length)
- 2Identifying the new head and tail efficiently
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.