Tutorialspoint
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)
Linked ListHCL TechnologiesApple
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a dummy node to handle edge cases and simplify the code.
 Step 2: Count the total number of nodes in the list.
 Step 3: Use three pointers to reverse each group of k nodes: prev (points to the node before current group), curr (points to the first node of current group), and next.
 Step 4: For each group, reverse k nodes using the standard three-pointer technique.
 Step 5: After reversing a group, connect the reversed segment back to the main list.
 Step 6: Update pointers to prepare for the next group.
 Step 7: If there are fewer than k nodes left, leave them as is.

Submitted Code :