Reverse LL in group of given size K

Linked-List FAQs (Hard) Hard

Given the head of a singly linked list containing integers, reverse the nodes of the list in groups of k and return the head of the modified list. If the number of nodes is not a multiple of k, then the remaining nodes at the end should be kept as is and not reversed.


Do not change the values of the nodes, only change the links between nodes.

Examples:

Input: head -> 1 -> 2 -> 3 -> 4 -> 5, k = 2

Output: head -> 2 -> 1 -> 4 -> 3 -> 5

Explanation: The groups 1 -> 2 and 3 -> 4 were reversed as 2 -> 1 and 4 -> 3.

Input: head -> 1 -> 2 -> 3 -> 4 -> 5, k = 3

Output: head -> 3 -> 2 -> 1 -> 4 -> 5

Explanation: The groups 1 -> 2 -> 3 were reversed as 3 -> 2 -> 1.

Note that 4 -> 5 was not reversed.

Input: head -> 6 -> 1 -> 2 -> 3 -> 4 -> 7, k = 4

Constraints

  • 1 <= k <= number of nodes in the linked list <= 105
  • -104 <= ListNode.val <= 104

Hints

  • A brute-force approach would involve: Extracting all nodes into an array (O(n) space). Reversing every k-sized subarray. Rebuilding the list (O(n) time).
  • Traverse the list to find k-sized groups. Reverse each k-group iteratively. Maintain pointers to link reversed groups correctly. If a remaining group has fewer than k nodes, keep it as is.

Company Tags

Ernst & Young Rakuten Morgan Stanley McKinsey & Company Epic Games Riot Games Chewy Flipkart Qualcomm Visa Robinhood Deloitte HCL Technologies NVIDIA Databricks Cloudflare Roblox eBay Airbnb Splunk Pinterest Seagate Technology Target Bungie Activision Blizzard Google Microsoft Amazon Meta Apple Netflix Adobe