Solving Leetcode Interviews in Seconds with AI: Reverse Nodes in k-Group
Introduction
In this blog post, we will explore how to solve the LeetCode problem "25" 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, reverse the nodes of the list k at a time, and return the modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed. Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [2,1,4,3,5] Example 2: Input: head = [1,2,3,4,5], k = 3 Output: [3,2,1,4,5] Constraints: The number of nodes in the list is n. 1 <= k <= n <= 5000 0 <= Node.val <= 1000 Follow-up: Can you solve the problem in O(1) extra memory space?
Explanation
Here's a solution to the k-group reverse linked list problem, focusing on efficiency and clarity.
- Iterative Reversal: The solution uses an iterative approach to reverse groups of k nodes. It maintains pointers to the previous group's tail, the current group's head, and performs local reversals within each group.
- Connectivity: After reversing each group, the code carefully connects the reversed group to the previous and next parts of the list.
Handling Insufficient Nodes: If a group has fewer than k nodes, it's left untouched.
Time & Space Complexity: O(n) time complexity, O(1) space complexity.
Code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseKGroup(head, k):
"""
Reverses the nodes of a linked list k at a time.
Args:
head: The head of the linked list.
k: The size of the group to reverse.
Returns:
The head of the modified linked list.
"""
dummy = ListNode(0) # Dummy node to handle the head case
dummy.next = head
prev_group_tail = dummy
while True:
# Check if there are at least k nodes remaining
current_group_head = prev_group_tail.next
#Temporary pointer to iterate over k nodes, if k nodes not present, break
temp = current_group_head
for _ in range(k):
if not temp:
return dummy.next # Return if fewer than k nodes remain
temp = temp.next
# Reverse the k nodes
prev = None
current = current_group_head
for _ in range(k):
next_node = current.next
current.next = prev
prev = current
current = next_node
# Connect the reversed group to the previous and next groups
prev_group_tail.next = prev # prev is now the head of the reversed group
current_group_head.next = current # current is now the node after the reversed group
#Update the prev group tail to point to last node of last reversed group
prev_group_tail = current_group_head # update prev_group_tail for the next group