Problem · Linked List

Reverse Nodes in K-Group

Learn this problem
HardAmazon logoAmazonFULLTIMEONSITE INTERVIEW
See Amazon hiring insights

Problem statement

Given the head head of a singly linked list and a positive integer k, reverse the nodes of the list in consecutive groups of exactly k nodes.

If fewer than k nodes remain at the end, leave that final group unchanged. Return the head of the transformed list.

You may change node links, but you must not change node values.

Function

reverseKGroup(head: ListNode, k: int) → ListNode

Examples

Example 1

head = [1,2,3,4,5]k = 2return = [2,1,4,3,5]

The complete groups [1, 2] and [3, 4] are reversed. The final one-node group remains unchanged.

Example 2

head = [1,2,3,4,5]k = 3return = [3,2,1,4,5]

The first three nodes form one complete group and are reversed. Only two nodes remain, so their order is preserved.

Constraints

  • The list contains between 1 and 5000 nodes.
  • -1000 <= node.val <= 1000
  • 1 <= k <= number of nodes
  • The input list is finite and contains no cycle.

More Amazon problems

drafts saved locally
/**
 * Definition for singly-linked list.
 * class ListNode {
 *   int val;
 *   ListNode next;
 * }
 */
public ListNode reverseKGroup(ListNode head, int k) {
  // write your code here
}
head[1,2,3,4,5]
k2
expected[2,1,4,3,5]
checking account