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 by reversing nodes in each group.
Iterate through the linked list in groups of size K
Reverse each group of nodes
Handle cases where the number of elements in th...read more
Help your peers!
Add answer anonymously...
Info Edge Senior Software Engineer interview questions & answers
A Senior Software Engineer was asked 2mo agoQ. Given two strings s and t, return the minimum window in s which will contain all...read more
A Senior Software Engineer was asked 12mo agoQ. Describe how you would build an MVC architecture.
A Senior Software Engineer was asked Q. Given a sorted array of integers nums and an integer target, write a function to...read more
Popular interview questions of Senior Software Engineer
A Senior Software Engineer was asked 2mo agoQ1. Given two strings s and t, return the minimum window in s which will contain all...read more
A Senior Software Engineer was asked 12mo agoQ2. Describe how you would build an MVC architecture.
A Senior Software Engineer was asked Q3. Given a sorted array of integers nums and an integer target, write a function to...read more
>
Info Edge Senior Software Engineer 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

