Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Reverse a Linked List in Groups

Medium Acceptance 57.08% Points 30

Given a linked list, the task is to reverse the nodes in groups of size k (where k is provided as input). If the total number of nodes is not a multiple of k, the remaining nodes at the end should be treated as a smaller group and reversed as well.

Examples
Example 1

Example 1

Input: Linked List: 10 -> 20 -> 30 -> 40 -> 50, k = 2

Output: 20 -> 10 -> 40 -> 30 -> 50

Explanation: The first 2 elements 10, 20 are reversed to 20, 10. these are reversed first. The last element 50 remains as is since the group size is less than k.

Example 2

Example 2

Input: Linked List: 5 -> 15 -> 25 -> 35 -> 45, k = 1

Output: 5 -> 15 -> 25 -> 35 -> 45

Explanation: Since k = 1, each group has only one node, so no changes are made. Resultant linked list: 5 -> 15 -> 25 -> 35 -> 45.

Constraints
  • 1 <= size of linked list <= 10^6
  • 1 <= data of nodes <= 10^6
  • 1 <= k <= size of linked list
Hints
  • Expected Time Complexity: O(n)
  • Expected Space Complexity: O(1)
Topics
Linked List
Companies
Amazon Microsoft Visa Walmart Adobe Paytm
Added 25 Mar 2025 57.08% acceptance
Ln 1, Col 1Sign in to save your code
10 20 30 40 50
2
20 10 40 30 50