
Problem
Solution
Submissions
Reverse Nodes in k-Group
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C# program to reverse the nodes of a linked list k at a time, where k is a positive integer. If the number of nodes is not a multiple of k, then the remaining nodes should remain as 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]
- Explanation:
- First group: [1,2] -> reverse -> [2,1]
- Second group: [3,4] -> reverse -> [4,3]
- Third group: [5] (less than k nodes, remain as is) -> [5]
- Result: [2,1,4,3,5]
Example 2
- Input: head = [1,2,3,4,5], k = 3
- Output: [3,2,1,4,5]
- Explanation:
- First group: [1,2,3] -> reverse -> [3,2,1]
- Second group: [4,5] (less than k nodes, remain as is) -> [4,5]
- Result: [3,2,1,4,5]
Constraints
- The number of nodes in the list is n
- 1 <= k <= n <= 5000
- 0 <= Node.val <= 1000
- Time Complexity: O(n)
- Space Complexity: O(1) extra space (excluding recursion stack)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Count k nodes to determine if there are enough to reverse
- Use the standard three-pointer technique to reverse a linked list segment
- Keep track of connections before and after each group
- For each group, reverse k nodes and update connections
- Handle the case when there are fewer than k nodes at the end