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

• Last Updated : 01 Jun, 2021

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:

Javascript


Output:
4 5 9 6

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

My Personal Notes arrow_drop_up