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
#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++)
{
string temp = to_string(v[i]);
str += temp;
if (j != k - 2)
i++;
}
stringstream check(str);
int s = 0;
check >> s;
arr.push_back(make_pair(s, index));
index++;
}
int u = 0;
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++;
}
}
for ( int i = 0; i < n; i++)
{
cout << v2[i] << " " ;
}
}
int main()
{
int n = 6;
vector< int > v = { 1, 32, 5, 6, 9, 3 };
int k = 2;
subarray_k(v, n, k);
return 0;
}
|
Last Updated :
23 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...