K-Sum in a Linked List
Submissions: 86   Accuracy:

1.17%

  Max. Score:

100

Given head of a linked list of integers and an integer k, your task is to modify the linked list as follows:

  1. Consider nodes in groups of size k. In every group, replace value of first node with group sum.

  2. Also, delete the elements of group except the first node.

  3. During traversal, if the remaining nodes in linkedlist are less than k then also do the above considering remaining nodes.

Input Format:
First line of input contains number of testcases T. For each testcase, first line contains length of linked list N and K. Second line contains elements of linked list.

Output Format:
For each testcase, print the modified linked list.

Constraints :
1 <= T <= 100

1 <= N <= 104
1 <= Elements of Linked List <= 106
1 <= K <= N

Example :
Input :
1

6 2
1 2 3 4 5 6

Output:
3 7 11

Explanation:
Testcase 1: k = 2.
We have denoted grouping of k elements by (). The elements inside () are summed.
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null
(1 -> 2) -> 3 -> 4 -> 5 -> 6 -> null
(3) -> 3 -> 4 -> 5 -> 6 -> null
3 -> (3 -> 4) -> 5 -> 6 -> null
3 -> (7) -> 5 -> 6 -> null
3 -> 7 -> (5 -> 6) -> null
3 -> 7 -> (11) -> null
3 -> 7 -> 11 -> null


to report an issue on this page.