Solving Leetcode Interviews in Seconds with AI: Rotate List
Introduction
In this blog post, we will explore how to solve the LeetCode problem "61" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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: The number of nodes in the list is in the range [0, 500]. -100 <= Node.val <= 100 0 <= k <= 2 * 109
Explanation
Here's an efficient approach to solve the linked list rotation problem:
- Calculate Length and Effective Rotation: Determine the length of the linked list. Then, compute the effective rotation
kby takingkmodulo the length. This handles cases wherekis larger than the list's length, preventing unnecessary rotations. - Locate New Head and Tail: Traverse the list to identify the new head and tail after the rotation. The new tail will be the
(length - k - 1)th node, and the new head will be the node after the new tail. Rearrange Pointers: Break the list at the new tail and connect the old tail to the original head.
Time Complexity: O(N), where N is the number of nodes in the linked list.
- Space Complexity: O(1) - constant extra space is used.
Code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def rotateRight(head, k):
if not head or not head.next or k == 0:
return head
# 1. Calculate the length of the linked list
length = 1
tail = head
while tail.next:
tail = tail.next
length += 1
# 2. Calculate the effective rotation value
k = k % length
if k == 0:
return head
# 3. Find the new tail and new head
new_tail_index = length - k - 1
new_tail = head
for _ in range(new_tail_index):
new_tail = new_tail.next
new_head = new_tail.next
# 4. Perform the rotation
new_tail.next = None # Break the list
tail.next = head # Connect the old tail to the original head
return new_head