Open In App

Split Array into subarrays of size K by filling elements

Last Updated : 18 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 <bits/stdc++.h>
using namespace std;

// Function to split the array
vector<vector<int> > divideArray(int nums[], 
                                 int K, int N)
{
    vector<vector<int> > 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<vector<int> >& 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<vector<int> > 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<ArrayList<Integer>> divideArray(int nums[], int K, int N) {
    ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> temp = new ArrayList<Integer>();
    for (int i = 0; i < N; i++) {
      temp.add(nums[i]);
      if (((i + 1) % K) == 0) {
        ans.add(temp);
        temp = new ArrayList<Integer>();
      }
    }
    // 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<ArrayList<Integer>> 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<ArrayList<Integer>> 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<List<int> > divideArray(int[] nums, int K,
                                      int N)
  {
    List<List<int> > ans = new List<List<int> >();
    ;
    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<List<int> > 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<List<int> > ans = divideArray(nums, K, N);
    printArray(ans);
    return 0;
  }
}

// This code is contributed by Taranpreet
JavaScript
 <script>
        // JavaScript code for the above approach 

        // Function to split the array
        function divideArray(nums, K, N) {
            let ans = [];
            let temp = [];
            for (let i = 0; i < N; i++) {
                temp.push(nums[i]);
                if (((i + 1) % K) == 0) {
                    ans.push(temp);
                    temp = [];
                }
            }
            
            // If last group doesn't have enough 
            // elements then add 0 to it
            if (temp.length != 0) {
                let a = temp.length;
                while (a != K) {
                    temp.push(0);
                    a++;
                }
                ans.push(temp);
            }
            return ans;
        }

        // Function to print answer
        function printArray(a) {
            let n = a.length;
            for (let i = 0; i < n; i++) {
                document.write("[ ");
                for (let j = 0; j < a[i].length; j++)
                    document.write(a[i][j] + " ");
                document.write("]");
            }
        }
        
        // Driver Code
        let nums = [1, 2, 3, 4, 5, 6, 7, 8];
        let N = nums.length;
        let K = 4;
        let ans = divideArray(nums, K, N);
        printArray(ans);

         // This code is contributed by Potta Lokesh
    </script>

 
 


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


 

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


 


Next Article

Similar Reads