Generate Array whose sum of all K-size subarrays divided by N leaves remainder X
Given three integer N, K and X, the task is to create an array of length N such that sum of all its K-length subarrays modulo N is X.
Examples:
Input: N = 6, K = 3, X = 3
Output: 9 6 6 9 6 6
Explanation:
All subarrays of length 3 and their respective sum%N values are as follows:
[9, 6, 6] Sum = 21 % 6 = 3
[6, 6, 9] sum = 21 % 6 = 3
[6, 9, 6] sum = 21 % 6 = 3
[9, 6, 6] sum = 21 % 6 = 3
Since all its subarrays have sum % N = X (=3), the generated array is valid.
Input: N = 4, K = 2, X = 2
Output: 6 4 6 4
Approach:
We can observe that in order to make the sum of any subarray of size K modulo N to be equal to X, the subarray needs to have a K – 1 elements equal to N and 1 element equal to N + X.
Illustration:
If N = 6, K = 3, X = 3
Here a K length subarray needs to be a permutation of {9, 6, 6} where 2 (K – 1) elements are divisible by 6 and 1 element has modulo N equal to X( 9%6 = 3)
Sum of subarray % N = (21 % 6) = 3 (same as X)
Hence, each K length
Hence, follow the steps below to solve the problem:
- Iterate i from 0 to N – 1, to print the ith element of the required subarray.
- If i % K is equal to 0, print N + X. Otherwise, for all other values of i, print N.
- This ensures that every possible K-length subarray has a sum K*N + X. Hence sum modulo N is X for all such subarrays.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void createArray( int n, int k, int x)
{
for ( int i = 0; i < n; i++) {
if (i % k == 0) {
cout << x + n << " " ;
}
else {
cout << n << " " ;
}
}
}
int main()
{
int N = 6, K = 3, X = 3;
createArray(N, K, X);
}
|
Java
import java.util.*;
class GFG{
static void createArray( int n, int k, int x)
{
for ( int i = 0 ; i < n; i++)
{
if (i % k == 0 )
{
System.out.print((x + n) + " " );
}
else
{
System.out.print(n + " " );
}
}
}
public static void main(String args[])
{
int N = 6 , K = 3 , X = 3 ;
createArray(N, K, X);
}
}
|
Python3
def createArray(n, k, x):
for i in range (n):
if (i % k = = 0 ):
print (x + n, end = " " )
else :
print (n, end = " " )
N = 6
K = 3
X = 3
createArray(N, K, X)
|
C#
using System;
class GFG{
static void createArray( int n, int k, int x)
{
for ( int i = 0; i < n; i++)
{
if (i % k == 0)
{
Console.Write((x + n) + " " );
}
else
{
Console.Write(n + " " );
}
}
}
public static void Main()
{
int N = 6, K = 3, X = 3;
createArray(N, K, X);
}
}
|
Javascript
<script>
function createArray(n, k, x)
{
for ( var i = 0; i < n; i++) {
if (i % k == 0) {
document.write( x + n + " " );
}
else {
document.write( n + " " );
}
}
}
var N = 6, K = 3, X = 3;
createArray(N, K, X);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
27 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...