Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Reverse a Linked List in Groups

Medium Acceptance 57.08% Points 30.00

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.

Hints
Hint 1
Expected Time Complexity: O(n)
Hint 2
Expected Space Complexity: O(1)
Constraints
  • 1 <= size of linked list <= 10^6
  • 1 <= data of nodes <= 10^6
  • 1 <= k <= size of linked list
Companies
Amazon Microsoft Visa Walmart Adobe + 1 more
Topics
Linked List
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions