GFG App
Open App
Browser
Continue

# Split Array into subarrays of size K by filling elements

Given an array nums[ ] of size N, the task is to split the array into groups of size K using the following procedure:

• The first group consists of the first K elements of the array, the second group consists of the next K element of the Array, and so on. Each element can be a part of exactly one group.
• For the last group, if the array does not have K elements remaining, use 0 to complete the group.

Examples:

Input: nums[ ] = {1,2,3,4,5,6,7,8}, K = 4
Output: [[1, 2, 3, 4] [ 5, 6, 7, 8]]
Explanation:
The first 4 element [1, 2, 3, 4] form the first group.
The next 4 elements [ 5, 6, 7, 8] form the second group.
Since all groups can be completely filled by element from the array, no need to use 0.

Input: nums[ ] = {3,2,5,7,9,1,3,5,7}, K = 2
Output: [[3, 2] ,[5, 7], [9,1], [3, 5], [7, 0]]
Explanation: The last group was one short of being of size 2. So, one 0 is used.

Approach: This is an easy implementation related problem. Follow the steps mentioned below to solve the problem:

• Maintain a temp vector which represents each group in the string.
• If the index i+1 is divisible by K then it can be concluded that group has ended with this ith index.
• Push the temp into the ans vector if group ends.
• Check whether last group has a size K or not.
• If it is not equal then add K – (len+1) sized fill with 0.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// Function to split the array` `vector > divideArray(``int` `nums[], ` `                                 ``int` `K, ``int` `N)` `{` `    ``vector > ans;` `    ``vector<``int``> temp;` `    ``for` `(``int` `i = 0; i < N; i++) {` `        ``temp.push_back(nums[i]);` `        ``if``(((i+1)%K)==0) {` `            ``ans.push_back(temp);` `            ``temp.clear();` `        ``}` `    ``}` `     ``// If last group doesn't have enough ` `    ``// elements then add 0 to it` `    ``if` `(!temp.empty()) {` `        ``int` `a = temp.size();` `        ``while` `(a != K) {` `            ``temp.push_back(0);` `            ``a++;` `        ``}` `        ``ans.push_back(temp);` `    ``}` `    ``return` `ans;` `}`   `// Function to print answer` `void` `printArray(vector >& a)` `{` `    ``int` `n = a.size();` `      ``cout << n;` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``cout << ``"[ "``;` `        ``for` `(``int` `j = 0; j < a[i].size(); j++)` `            ``cout << a[i][j] << ``" "``;      ` `        ``cout << ``"]"``;` `    ``}` `}` `// Driver Code` `int` `main()` `{` `    ``int` `nums[] = { 1, 2, 3, 4, 5, 6, 7, 8 };` `    ``int` `N = ``sizeof``(nums) / ``sizeof``(nums[0]);` `    ``int` `K = 4;` `    ``vector > ans ` `        ``= divideArray(nums, K, N);` `    ``printArray(ans);` `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `import` `java.util.ArrayList;`   `class` `GFG {`   `  ``// Function to split the array` `  ``static` `ArrayList> divideArray(``int` `nums[], ``int` `K, ``int` `N) {` `    ``ArrayList> ans = ``new` `ArrayList>();` `    ``ArrayList temp = ``new` `ArrayList();` `    ``for` `(``int` `i = ``0``; i < N; i++) {` `      ``temp.add(nums[i]);` `      ``if` `(((i + ``1``) % K) == ``0``) {` `        ``ans.add(temp);` `        ``temp = ``new` `ArrayList();` `      ``}` `    ``}` `    ``// If last group doesn't have enough` `    ``// elements then add 0 to it` `    ``if` `(temp.size() != ``0``) {` `      ``int` `a = temp.size();` `      ``while` `(a != K) {` `        ``temp.add(``0``);` `        ``a++;` `      ``}` `      ``ans.add(temp);` `    ``}` `    ``return` `ans;` `  ``}`   `  ``// Function to print answer` `  ``static` `void` `printArray(ArrayList> a) {` `    ``int` `n = a.size();` `    ``for` `(``int` `i = ``0``; i < n; i++) {` `      ``System.out.print(``"[ "``);` `      ``for` `(``int` `j = ``0``; j < a.get(i).size(); j++)` `        ``System.out.print(a.get(i).get(j) + ``" "``);` `      ``System.out.print(``"]"``);` `    ``}` `  ``}`   `  ``// Driver Code` `  ``public` `static` `void` `main(String args[]) {` `    ``int` `nums[] = { ``1``, ``2``, ``3``, ``4``, ``5``, ``6``, ``7``, ``8` `};` `    ``int` `N = nums.length;` `    ``int` `K = ``4``;` `    ``ArrayList> ans = divideArray(nums, K, N);` `    ``printArray(ans);` `  ``}` `}`   `// This code is contributed by saurabh_jaiswal.`

## Python3

 `# python3 program for the above approach`   `# Function to split the array` `def` `divideArray(nums, K, N):`   `    ``ans ``=` `[]` `    ``temp ``=` `[]` `    ``for` `i ``in` `range``(``0``, N):` `        ``temp.append(nums[i])` `        ``if``(((i``+``1``) ``%` `K) ``=``=` `0``):` `            ``ans.append(temp.copy())` `            ``temp.clear()`   `    ``# If last group doesn't have enough` `    ``# elements then add 0 to it` `    ``if` `(``len``(temp) !``=` `0``):` `        ``a ``=` `len``(temp)` `        ``while` `(a !``=` `K):` `            ``temp.append(``0``)` `            ``a ``+``=` `1`   `        ``ans.append(temp)`   `    ``return` `ans`   `# Function to print answer` `def` `printArray(a):`   `    ``n ``=` `len``(a)` `    ``for` `i ``in` `range``(``0``, n):` `        ``print``(``"[ "``, end``=``"")` `        ``for` `j ``in` `range``(``0``, ``len``(a[i])):` `            ``print``(a[i][j], end``=``" "``)` `        ``print``(``"]"``, end``=``"")`   `# Driver Code` `if` `__name__ ``=``=` `"__main__"``:`   `    ``nums ``=` `[``1``, ``2``, ``3``, ``4``, ``5``, ``6``, ``7``, ``8``]` `    ``N ``=` `len``(nums)` `    ``K ``=` `4` `    ``ans ``=` `divideArray(nums, K, N)` `    ``printArray(ans)`   `# This code is contributed by rakeshsahni`

## C#

 `// C# program for the above approach` `using` `System;` `using` `System.Collections.Generic;` `class` `GFG ` `{`   `  ``// Function to split the array` `  ``static` `List > divideArray(``int``[] nums, ``int` `K,` `                                      ``int` `N)` `  ``{` `    ``List > ans = ``new` `List >();` `    ``;` `    ``List<``int``> temp = ``new` `List<``int``>();` `    ``for` `(``int` `i = 0; i < N; i++) {` `      ``temp.Add(nums[i]);` `      ``if` `(((i + 1) % K) == 0) {` `        ``ans.Add(temp);` `        ``temp = ``new` `List<``int``>();` `      ``}` `    ``}` `    ``// If last group doesn't have enough` `    ``// elements then add 0 to it` `    ``if` `(temp.Count != 0) {` `      ``int` `a = temp.Count;` `      ``while` `(a != K) {` `        ``temp.Add(0);` `        ``a++;` `      ``}` `      ``ans.Add(temp);` `    ``}` `    ``return` `ans;` `  ``}`   `  ``// Function to print answer` `  ``static` `void` `printArray(List > a)` `  ``{` `    ``int` `n = a.Count;` `    ``for` `(``int` `i = 0; i < n; i++) {` `      ``Console.Write(``"[ "``);` `      ``for` `(``int` `j = 0; j < a[i].Count; j++)` `        ``Console.Write(a[i][j] + ``" "``);` `      ``Console.Write(``"]"``);` `    ``}` `  ``}` `  `  `  ``// Driver Code` `  ``public` `static` `int` `Main()` `  ``{` `    ``int``[] nums = ``new` `int``[] { 1, 2, 3, 4, 5, 6, 7, 8 };` `    ``int` `N = nums.Length;` `    ``int` `K = 4;` `    ``List > ans = divideArray(nums, K, N);` `    ``printArray(ans);` `    ``return` `0;` `  ``}` `}`   `// This code is contributed by Taranpreet`

## Javascript

 ``

Output

`[ 1 2 3 4 ][ 5 6 7 8 ]`

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

My Personal Notes arrow_drop_up