LeetCode-in-Ruby.github.io

25. Reverse Nodes in k-Group

Hard

Given a linked list, reverse the nodes of a linked list k at a time and return its 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]

Example 3:

Input: head = [1,2,3,4,5], k = 1

Output: [1,2,3,4,5]

Example 4:

Input: head = [1], k = 1

Output: [1]

Constraints:

Follow-up: Can you solve the problem in O(1) extra memory space?

Solution

# Definition for singly-linked list.
# class ListNode
#     attr_accessor :val, :next
#     def initialize(val = 0, _next = nil)
#         @val = val
#         @next = _next
#     end
# end
# @param {ListNode} head
# @param {Integer} k
# @return {ListNode}
def reverse_k_group(head, k)
  return head if head.nil? || head.next.nil? || k == 1

  j = 0
  len = head

  # Loop for checking the length of the linked list.
  # If the linked list is less than k, then return as it is.
  while j < k
    return head if len.nil?

    len = len.next
    j += 1
  end

  # Reverse linked list logic applied here.
  c = head
  n = nil
  prev = nil
  i = 0

  # Traverse the while loop for K times to reverse the node in K groups.
  while i != k
    n = c.next
    c.next = prev
    prev = c
    c = n
    i += 1
  end

  # head points to the first node of the reversed K group,
  # which is now going to point to the next K group linked list.
  # Recursion for further remaining linked list.
  head.next = reverse_k_group(n, k)
  prev
end