Partition a Linked List into K continuous groups with difference in their sizes at most 1

Given a linked list consisting of N nodes and an integer K, the task is to split the given Linked List into K continuous groups such that the difference between the size of the adjacent groups after splitting is at most 1 and the groups are sorted in descending order of their lengths.

Note: A group with 0 elements can also be formed.

Examples:

Input: 1 ? 2 ? 3 ? 4, K = 5
Output: {{1}, {2}, {3}, {4}, {}}
Explanation: Required splits are {{1 -> NULL}, {2 -> NULL}, {3 -> NULL}, {4 -> NULL}, {NULL}}.

Input: LL: 1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 ? 8, K = 3
Output: {{1, 2, 3}, {4, 5, 6}, {7, 8}}

Approach: The given problem can be solved based on the observation that forming first N % K groups of size (N / K + 1) and the remaining K – (N % K) groups of size N / K satisfies the conditions. Follow the steps below to solve the problem:

• Initialize a vector of the linked list, says ans, that stores the K groups.
• Store the value of N / K and N % K in the variables, say L and R.
• Traverse the given linked list and perform the following steps:
• Store the value of L in a variable say X and the value of head in the variable say currHead and last.
• If the value of R is positive, then update the value of head to head->next.
• Iterate a loop until X is non-zero and perform the following steps:
• If the last node is the same as the head node then move the head node to the next node.
• Otherwise, join the links between the last node and the head node and update the last to head, and move the head node to the next node.
• Push the current Linked List as the currentHead in the vector ans[].
• If the value of K is greater than 0, then push the NULL Linked List in ans and decrement K by 1.
• After completing the above steps, print the elements of all the Linked List stored in the vector ans[].

Below is the implementation of the above approach:

C++

Java

Python3

C#

Javascript



Output:
{{1  2  3  }, {4  5  6  }, {7  8  }}

Time Complexity: O(N)
Auxiliary Space: O(N)

Previous
Next