Independence Day Sale! Unlock 40% OFF on All Job-Oriented Training Programs – Limited Time Only! Offer Ending in
D
H
M
S
Get Now
Problem Submissions Solution

Reverse a Linked List in Groups

Difficulty: Medium

Acceptance: %

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.

Topics

Companies

Articles

Examples:

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.

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.

Expected Time Complexity: O(n)

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
Locked Content
Access Restricted: Please Login to access the code editor and test cases.