HARD NC#45 Linked List

25. Reverse Nodes in k-Group

๐Ÿ“– Problem

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. It is guaranteed that the number of nodes in the list is divisible by k. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. You must solve the problem in O(1) extra memory space.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ Find kth node in each group
  • โ†’ Reverse each k-group in place
  • โ†’ Connect previous group to current reversed group
  • โ†’ Use helper function to find kth node from any starting point
  • โ†’ Time: O(n), Space: O(1)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขFind kth node in each group
  • โ€ขReverse each k-group in place
  • โ€ขConnect previous group to current reversed group

Common Pitfalls

  • โ€ขUse helper function to find kth node from any starting point
  • โ€ขTime: O(n), Space: O(1)

๐Ÿงช Test Cases

Test Case 1
Not run
Input:
reverseKGroup(arrayToList([1,2,3,4,5]), 2);
Expected:
{"val":2,"next":{"val":1,"next":{"val":4,"next":{"val":3,"next":{"val":5,"next":null}}}}}
Test Case 2
Not run
Input:
reverseKGroup(arrayToList([1,2,3,4,5]), 3);
Expected:
{"val":3,"next":{"val":2,"next":{"val":1,"next":{"val":4,"next":{"val":5,"next":null}}}}}
Test Case 3
Not run
Input:
reverseKGroup(head: ListNode | null, k: number);
Expected:
Computed from hidden reference

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit