LeetcodeJul 13, 2025

Reverse Nodes in k-Group

Hazrat Ali

Leetcode

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]


Solution
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
const reverseKGroup = (head, k) => {
 
  if (getLength(head) < k) {
    return head;
  }
 
  let prev = null;
  let curr = head;
  let count = k;

  while (curr && count-- > 0) {
    let next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
  }

  head.next = reverseKGroup(curr, k);

  return prev;
};

const getLength = head => {
  let count = 0;
  let p = head;

  while (p) {
    p = p.next;
    count++;
  }

  return count;
};


Comments