# Subarray of length K having concatenation of its elements divisible by X

Given an array arr[] consisting of N positive integers, the task is to find a subarray of length K such that concatenation of each element of the subarray is divisible by X. If no such subarray exists, then print “-1”. If more than one such subarray exists, print any one of them.

Examples:

Input: arr[] = {1, 2, 4, 5, 9, 6, 4, 3, 7, 8}, K = 4, X = 4
Output: 4 5 9 6
Explanation:
The elements of the subarray {4, 5, 9, 6} concatenates to form 4596, which is divisible by 4.

Input: arr[] = {2, 3, 5, 1, 3}, K = 3, X = 6
Output: -1

Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays of length K and print that subarray whose concatenation of elements is divisible by X. If no such subarray exists, print “-1”. Otherwise, print any of these subarrays.

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized using the Sliding Window Technique. Follow the steps below to solve the problem:

1. Generate a number by concatenating the first K array elements. Store it in a variable, say num.
2. Check if the number generated is divisible by X or not. If found to be true, then print the current subarray.
3. Otherwise, traverse the array over the range [K, N] and for each element follow the steps below:
• Add the digits of the element arr[i] to the variable num.
• Remove the digits of the element arr[i – K] from the front of the num.
• Now check if the current number formed is divisible by X or not. If found to be true, then print the current subarray in the range [i – K, i].
• Otherwise, check for the next subarray.
4. If no such subarray exists, then print “-1”.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach`   `#include ` `using` `namespace` `std;`   `// Function to return the starting` `// index of the subarray whose` `// concatenation is divisible by X` `int` `findSubarray(vector<``int``> arr,` `                 ``int` `K, ``int` `X)` `{` `    ``int` `i, num = 0;`   `    ``// Generate the concatenation` `    ``// of first K length subarray` `    ``for` `(i = 0; i < K; i++) {` `        ``num = num * 10 + arr[i];` `    ``}`   `    ``// If num is divisible by X` `    ``if` `(num % X == 0) {` `        ``return` `0;` `    ``}`   `    ``// Traverse the remaining array` `    ``for` `(``int` `j = i; j < arr.size(); j++) {`   `        ``// Append the digits of arr[i]` `        ``num = (num % (``int``)``pow``(10, j - 1))` `                  ``* 10` `              ``+ arr[j];`   `        ``// If num is divisible by X` `        ``if` `(num % X == 0) {` `            ``return` `j - i + 1;` `        ``}` `    ``}`   `    ``// No subarray exists` `    ``return` `-1;` `}`   `// Function to print the subarray in` `// the range [answer, answer + K]` `void` `print(vector<``int``> arr, ``int` `answer,` `           ``int` `K)` `{` `    ``// No such subarray exists` `    ``if` `(answer == -1) {` `        ``cout << answer;` `    ``}`   `    ``// Otherwise` `    ``else` `{`   `        ``// Print the subarray in the` `        ``// range [answer, answer + K]` `        ``for` `(``int` `i = answer;` `             ``i < answer + K; i++) {` `            ``cout << arr[i] << ``" "``;` `        ``}` `    ``}` `}`   `// Driver Code` `int` `main()` `{` `    ``// Given array arr[]` `    ``vector<``int``> arr = { 1, 2, 4, 5, 9,` `                        ``6, 4, 3, 7, 8 };`   `    ``int` `K = 4, X = 4;`   `    ``// Function Call` `    ``int` `answer = findSubarray(arr, K, X);`   `    ``// Function Call to print subarray` `    ``print(arr, answer, K);`   `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `import` `java.io.*;` `import` `java.util.*;`   `class` `GFG{`   `// Function to return the starting` `// index of the subarray whose` `// concatenation is divisible by X` `static` `int` `findSubarray(ArrayList arr, ``int` `K,` `                                                ``int` `X)` `{` `    ``int` `i, num = ``0``;`   `    ``// Generate the concatenation` `    ``// of first K length subarray` `    ``for``(i = ``0``; i < K; i++) ` `    ``{` `        ``num = num * ``10` `+ arr.get(i);` `    ``}`   `    ``// If num is divisible by X` `    ``if` `(num % X == ``0``)` `    ``{` `        ``return` `0``;` `    ``}`   `    ``// Traverse the remaining array` `    ``for``(``int` `j = i; j < arr.size(); j++)` `    ``{` `        `  `        ``// Append the digits of arr[i]` `        ``num = (num % (``int``)Math.pow(``10``, j - ``1``)) *` `                ``10` `+ arr.get(j);`   `        ``// If num is divisible by X` `        ``if` `(num % X == ``0``)` `        ``{` `            ``return` `j - i + ``1``;` `        ``}` `    ``}`   `    ``// No subarray exists` `    ``return` `-``1``;` `}`   `// Function to print the subarray in` `// the range [answer, answer + K]` `static` `void` `print(ArrayList arr, ``int` `answer,` `                                          ``int` `K)` `{` `    `  `    ``// No such subarray exists` `    ``if` `(answer == -``1``)` `    ``{` `        ``System.out.println(answer);` `    ``}`   `    ``// Otherwise` `    ``else` `    ``{` `        `  `        ``// Print the subarray in the` `        ``// range [answer, answer + K]` `        ``for``(``int` `i = answer; i < answer + K; i++)` `        ``{` `            ``System.out.print(arr.get(i) + ``" "``);` `        ``}` `    ``}` `}`   `// Driver Code` `public` `static` `void` `main(String[] args)` `{` `    `  `    ``// Given array arr[]` `    ``ArrayList arr = ``new` `ArrayList(` `        ``Arrays.asList(``1``, ``2``, ``4``, ``5``, ``9``, ``6``, ``4``, ``3``, ``7``, ``8``));`   `    ``int` `K = ``4``, X = ``4``;`   `    ``// Function call` `    ``int` `answer = findSubarray(arr, K, X);`   `    ``// Function call to print subarray` `    ``print(arr, answer, K);` `}` `}`   `// This code is contributed by akhilsaini`

## Python3

 `# Python3 program for the above approach`   `# Function to return the starting` `# index of the subarray whose` `# concatenation is divisible by X` `def` `findSubarray(arr, K, X):`   `    ``num ``=` `0`   `    ``# Generate the concatenation` `    ``# of first K length subarray` `    ``for` `i ``in` `range``(``0``, K):` `        ``num ``=` `num ``*` `10` `+` `arr[i]`   `    ``# If num is divisible by X` `    ``if` `num ``%` `X ``=``=` `0``:` `        ``return` `0` `      `  `    ``i ``=` `K` `    `  `    ``# Traverse the remaining array` `    ``for` `j ``in` `range``(i, ``len``(arr)):` `        `  `        ``# Append the digits of arr[i]` `        ``num ``=` `((num ``%` `int``(``pow``(``10``, j ``-` `1``))) ``*` `                ``10` `+` `arr[j])`   `        ``# If num is divisible by X` `        ``if` `num ``%` `X ``=``=` `0``:` `            ``return` `j ``-` `i ``+` `1`   `    ``# No subarray exists` `    ``return` `-``1`   `# Function to print the subarray in` `# the range [answer, answer + K]` `def` `print_subarray(arr, answer, K):` `    `  `    ``# No such subarray exists` `    ``if` `answer ``=``=` `-``1``:` `        ``print``(answer)`   `    ``# Otherwise` `    ``else``:` `        `  `        ``# Print the subarray in the` `        ``# range [answer, answer + K]` `        ``for` `i ``in` `range``(answer, answer ``+` `K):` `            ``print``(arr[i], end ``=` `" "``)`   `# Driver Code` `if` `__name__ ``=``=` `"__main__"``:` `    `  `    ``# Given array arr[]` `    ``arr ``=` `[ ``1``, ``2``, ``4``, ``5``, ``9``, ` `            ``6``, ``4``, ``3``, ``7``, ``8` `]`   `    ``K ``=` `4` `    ``X ``=` `4`   `    ``# Function call` `    ``answer ``=` `findSubarray(arr, K, X)`   `    ``# Function call to print subarray` `    ``print_subarray(arr, answer, K)`   `# This code is contributed by akhilsaini`

## C#

 `// C# program for the above approach` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG{`   `// Function to return the starting` `// index of the subarray whose` `// concatenation is divisible by X` `static` `int` `findSubarray(List<``int``> arr, ``int` `K,` `                                       ``int` `X)` `{` `    ``int` `i, num = 0;`   `    ``// Generate the concatenation` `    ``// of first K length subarray` `    ``for``(i = 0; i < K; i++)` `    ``{` `        ``num = num * 10 + arr[i];` `    ``}`   `    ``// If num is divisible by X` `    ``if` `(num % X == 0) ` `    ``{` `        ``return` `0;` `    ``}`   `    ``// Traverse the remaining array` `    ``for``(``int` `j = i; j < arr.Count; j++)` `    ``{` `        `  `        ``// Append the digits of arr[i]` `        ``num = (num % (``int``)Math.Pow(10, j - 1)) * ` `                ``10 + arr[j];`   `        ``// If num is divisible by X` `        ``if` `(num % X == 0) ` `        ``{` `            ``return` `j - i + 1;` `        ``}` `    ``}` `    `  `    ``// No subarray exists` `    ``return` `-1;` `}`   `// Function to print the subarray in` `// the range [answer, answer + K]` `static` `void` `print(List<``int``> arr, ``int` `answer, ` `                                 ``int` `K)` `{` `    `  `    ``// No such subarray exists` `    ``if` `(answer == -1) ` `    ``{` `        ``Console.WriteLine(answer);` `    ``}`   `    ``// Otherwise` `    ``else` `    ``{` `        `  `        ``// Print the subarray in the` `        ``// range [answer, answer + K]` `        ``for``(``int` `i = answer; i < answer + K; i++)` `        ``{` `            ``Console.Write(arr[i] + ``" "``);` `        ``}` `    ``}` `}`   `// Driver Code` `static` `public` `void` `Main()` `{` `    `  `    ``// Given array arr[]` `    ``List<``int``> arr = ``new` `List<``int``>(){ 1, 2, 4, 5, 9,` `                                     ``6, 4, 3, 7, 8 };`   `    ``int` `K = 4, X = 4;`   `    ``// Function call` `    ``int` `answer = findSubarray(arr, K, X);`   `    ``// Function call to print subarray` `    ``print(arr, answer, K);` `}` `}`   `// This code is contributed by akhilsaini`

Output:

```4 5 9 6

```

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up 