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)
๐งญ Prerequisites
๐ ๏ธ 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
๐ค Output