Reverse Linked List in Groups of K
You are provided with a linked list containing 'N' nodes and an integer 'K'. The task is to reverse the linked list in groups of size K, which means reversing the nodes in each group (1,K),(K+1,2*K), etc.
Example:
Input:
List: [1, 2, 3, 4, 5, 6], K = 2
Output:
[2, 1, 4, 3, 6, 5]
Explanation:
The nodes are reversed in pairs: [1, 2] -> [2, 1], [3, 4] -> [4, 3], [5, 6] -> [6, 5].
Constraints:
- 1 <= T <= 100
- 1 <= N <= 10^4
- 1 <= K <= 10^4
- Time Limit: 1sec
Input:
The first line of input contains an integer 'T' representing the number of test cases. Each test case follows with:
1. A line containing a linked list where elements are separated by spaces and the list is terminated by -1.
2. A line containing the integer K.
Output:
For each test case, output the modified linked list elements, separated by spaces, on a new line.
Note:
- If the number of elements in the last group cannot be evenly divided by K, reverse that last group. For example, for list [1, 2, 3, 4, 5] and K = 3, the output is [3, 2, 1, 5, 4].
- All node values in the linked list are distinct.

AnswerBot
4mo
Reverse a linked list in groups of size K.
Iterate through the linked list in groups of size K.
Reverse each group of nodes.
Handle cases where the number of elements in the last group is less than K.
Help your peers!
Add answer anonymously...
Josh Technology Group Software Developer Intern interview questions & answers
A Software Developer Intern was asked 3mo agoQ. Given a linked list, how do you ensure that it is in decreasing order?
A Software Developer Intern was asked 3mo agoQ. Given a random node in a BST, how do you check if a given element is part of the...read more
A Software Developer Intern was asked Q. Merge Two Binary Trees Problem Statement You are given the roots of two binary t...read more
Popular interview questions of Software Developer Intern
A Software Developer Intern was asked 3mo agoQ1. Given a linked list, how do you ensure that it is in decreasing order?
A Software Developer Intern was asked 3mo agoQ2. Given a random node in a BST, how do you check if a given element is part of the...read more
A Software Developer Intern was asked Q3. Merge Two Binary Trees Problem Statement You are given the roots of two binary t...read more
>
Josh Technology Group Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

