You are given an integer array 'A' of length 'N'. Your task is to find a subarray A[L, R] for which following conditions hold:
1 <= L < R <= N.
Let S = A[L] + A[L+1] + …. + A[R-1] + A[R], then S % K = 0.
Your task is to find whether there exists a subarray for which above conditions hold. If such a subarray is found, return 1, else return 0.
The first line contains 'T', denoting the number of tests.
For each Test :
The first line contains two space-separated integers, 'N' and 'K', denoting the size of array and number K, respectively.
The second line contains an array 'A' of length 'N'.
Output Format:
For each test, print an integer (either 0 or 1), denoting whether a subarray fulfilling given conditions is found.
Note:
You are not required to print the expected output. It has already been taken care of. Just implement the function.
1 <= 'T' <= 10
1 <= 'N' <= 10^5
1 <= 'K' <= 10^9
0 <= A[i] <= 10^9 i ∈ (1, N)
Note - Sum of 'N' over all test cases does not exceed 10^5.
Time Limit: 1 sec
2
5 6
3 2 4 6 7
5 13
23 2 6 4 7
1
0
For case 1:
If L = 2 and R = 3, both of the given conditions are true.
S = 2 + 4 = 6.
S % K = 6 % 6 = 0.
For Case 2:
No subarray is found for which S % K = 0.
3
3 2
1 1 1
4 2
3 2 1 3
5 7
2 4 2 0 2
1
1
0
Can you check for each subarray sum?
Approach: Run two nested loops to select each possible subarray (of length at least 2), and if its sum is a multiple of value 'K', return 1. At last, if no subarray is found, return 0.
Algorithm:
O(N ^ 2), where 'N' is the number of elements in the array 'A'.
We ran two nested loops and checked for each subarray sum. Hence overall time complexity becomes O(N ^ 2).
O(1).
We are using only constant space. Hence overall space complexity is O(1).