Taro Logo

Reverse Nodes in k-Group

#2 Most AskedHard
Topics:
Linked Lists

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?

Solution


Clarifying Questions

When 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:

  1. What should be returned if the linked list is empty or if $k$ is greater than the total number of nodes in the list?
  2. Can $k$ be less than 1, and if so, how should the function behave?
  3. Are the node values guaranteed to be standard integers, and can they contain duplicates or negative numbers?
  4. Should the reversal be performed in-place using constant extra space ($O(1)$ auxiliary memory), or is recursion stack space allowed?
  5. If the total number of nodes is not a multiple of $k$, do the leftover nodes at the end remain in their original relative order?

Brute Force Solution

Approach

Imagine you have a chain of linked items and you want to flip every small group of a specific size. The brute force strategy involves walking through the entire chain to find each small group and meticulously flipping the items inside it, starting from the very beginning.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first item in the chain.
  2. Count forward by the required group size to see if you have a complete group to flip.
  3. If you do not have enough items left to make a full group, leave the remaining items exactly as they are.
  4. If you do have a full group, carefully reverse the connections between the items inside this specific group so they point backward.
  5. Carefully reconnect the newly flipped group to the rest of the chain.
  6. Move past the group you just finished flipping and repeat the counting and flipping process for the next group.
  7. Keep repeating this process until you reach the end of the entire chain.

Code Implementation

class ListNode:
    def __init__(self, item_value=0, next_node=None):
        self.item_value = item_value
        self.next_node = next_node

def reverse_k_group(head_node, group_size):
    current_node = head_node
    group_counter = 0
    
    # We check if there are at least k nodes remaining to form a valid group for reversal
    while current_node and group_counter < group_size:
        current_node = current_node.next_node
        group_counter += 1
        
    if group_counter == group_size:
        current_node = reverse_k_group(current_node, group_size)
        
        # We reverse the current group of nodes since we confirmed we have a full group
        while group_counter > 0:
            next_element = head_node.next_node
            head_node.next_node = current_node
            current_node = head_node
            head_node = next_element
            group_counter -= 1
            
        head_node = current_node
        
    # We return the original head if a full group could not be formed, leaving tail untouched
    return head_node

Big(O) Analysis

Time Complexity
O(n) – To reverse the nodes in k-group, the algorithm traverses the entire linked list of size n to check and count each group of size k. Within this traversal, every individual node is visited a constant number of times during the local reversal process. Since the k-group size is a constant factor, each node is touched roughly once or twice as we move through the chain. Summing these linear operations across all n elements yields approximately n operations, which simplifies to O(n).
Space Complexity
O(1) – The iterative approach to reversing nodes in k-groups relies solely on a few constant pointers and integer variables to keep track of the current group, previous nodes, and next connections. Because no auxiliary data structures like arrays, hash maps, or recursion stacks are utilized, the extra memory required remains entirely constant regardless of the total number of elements N in the linked list.

Optimal Solution

Approach

The optimal approach solves this problem by processing the line of connected items in small, fixed-size chunks. It carefully reverses the direction of pointers within each chunk one by one, while keeping track of where the next chunk begins so nothing gets lost.

Here's how the algorithm would work step-by-step:

  1. Look at the very beginning of the line of items and check ahead to see if there is a complete group of the required size waiting to be processed.
  2. If there are not enough items left to form a complete group, leave the remaining items exactly as they are and finish the process.
  3. If a complete group is found, prepare to reverse the connections between the items inside this specific group.
  4. Carefully flip the direction of the links between the items one by one, making the last item in the group point backward to the first.
  5. Connect the newly flipped group to the part of the line that was already processed behind it.
  6. Remember to connect the start of this flipped group to the rest of the upcoming items ahead.
  7. Shift your attention forward to the next section of the line and repeat the entire process until no complete groups are left.

Code Implementation

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n be the total number of nodes in the linked list. The algorithm traverses the linked list to check for complete groups of size k and reverses the pointers within those groups. Each individual node is visited a constant number of times—once to check if it belongs to a valid group during the initial lookahead phase, and at most once more during the pointer-reversal step. This means the total number of operations scales linearly with the number of nodes, closely approximating n steps in total, which simplifies to O(n).
Space Complexity
O(1) – The optimal iterative approach for reversing nodes in k-groups relies entirely on a few constant pointers to track the current group, previous group tail, and next group start. No additional data structures, temporary lists, or recursive stack frames are allocated as the input size N grows. Because memory usage remains constant regardless of the total number of elements in the linked list, the auxiliary space complexity is strictly O(1).

Edge Cases

Null head or empty linked list
How to Handle:
Return the head immediately without performing any operations since no nodes exist to reverse.
k is equal to 1
How to Handle:
Return the original head unchanged because reversing groups of one node leaves the list identical.
k is greater than the total number of nodes in the list
How to Handle:
Leave the entire list unmodified and return the head as the node count is less than k.
Total number of nodes is an exact multiple of k
How to Handle:
Process and reverse every single group successfully without leaving any trailing nodes behind.
List length is smaller than k
How to Handle:
Check the remaining node count before each reversal attempt and keep the tail nodes as they are if they fall short of k.
k equals the exact length of the linked list
How to Handle:
Reverse the entire linked list from the head to the tail and return the new head as the final result.
Nodes contain duplicate values, negative numbers, or extreme values
How to Handle:
Ignore node values entirely and only manipulate the pointer references to ensure values do not affect pointer logic.
Large linked list approaching memory constraints
How to Handle:
Use an iterative approach with O(1) extra space to prevent stack overflow errors that recursion might cause.
0/3 completed