Informatica Coding Round Question

Given an array with n elements and an integer k. Divide the array into subarrays, each of them containing k elements.For example: 
Input: arr[]={1, 32, 5, 6, 9, 3} and k=2

The subarrays will have elements:
{132}, {56}, {93}.

Now sort these subarrays as {56}, {93}, {132}. Merge these subarrays together and display them as the elements of original array in sorted order as
Final output: arr[]={5, 6, 9, 3, 1, 32} 

Examples: 

Input : 
arr[]={1, 32, 5, 6, 9, 3} 
k=2 
Output : 
arr[]={5, 6, 9, 3, 1, 32}

Below is the implementation of the above idea:



CPP

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program implemenation of the above idea
 
#include <bits/stdc++.h>
using namespace std;
void subarray_k(vector<int> v, int n, int k)
{
    int sum = 0;
    int index;
    string str = "";
    vector<pair<int, int> > arr;
    for (int i = 0; i < n - 1; i++)
    {
        index = i;
        str = to_string(v[i]);
        i++;
        for (int j = 0; j < k - 1; j++)
        {
            // Conversion of array elements(integers) to
            // string for easy concatination
            string temp = to_string(v[i]);
            str += temp;
            if (j != k - 2)
                i++;
        }
        stringstream check(str);
        int s = 0;
 
        // Conversion of concatinated string to integer
        check >> s;
        arr.push_back(make_pair(s, index));
        index++;
    }
    int u = 0;
   
    // Sorting of array
    sort(arr.begin(), arr.end());
    vector<int> v2;
    for (int i = 0; i < (n / k); i++) {
        u = 0;
        int j = arr[i].second;
        while (u < k) {
            int a = v[j];
            v2.push_back(a);
            u++;
            j++;
        }
    }
   
    // print
    for (int i = 0; i < n; i++)
    {
        cout << v2[i] << " ";
    }
}
 
// Driver code
int main()
{
    int n = 6;
    vector<int> v = { 1, 32, 5, 6, 9, 3 };
    int k = 2;
 
    // Function call
    subarray_k(v, n, k);
    return 0;
    // This code is contributed by Siddhant Thapliyal
}

chevron_right


Output

5 6 9 3 1 32 


Write your Interview Experience or mail it to contribute@geeksforgeeks.org




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.