Given an array of size N, we need to find smallest sized subarray whose sum is divisible by array size N.
Input : arr = [1, 1, 2, 2, 4, 2] Output : [2 4] Size of array, N = 6 Following subarrays have sum as multiple of N [1, 1, 2, 2], [2, 4], [1, 1, 2, 2, 4, 2] The smallest among all is [2 4]
We can solve this problem considering below facts,
Let S[i] denotes sum of first i elements i.e. S[i] = a + a .. + a[i] Now subarray arr(i, i + x) has sum multiple of N then, (arr(i] + arr[i+1] + .... + arr[i + x])) % N = 0 (S[i+x] – S[i] ) % N = 0 S[i] % N = S[i + x] % N
We need to find the minimum value of x for which the above condition holds. This can be implemented in single iteration with O(N) time-complexity using another array modIdx of size N. Array modIdx is initialized with all elements as -1. modIdx[k] is to be updated with i in each iteration, where k = sum % N.
Now in each iteration we need to update modIdx[k] according to the value of sum % N.
We need to check two things,
If at any instant k = 0 and it is the first time we are updating modIdx (i.e. modIdx was -1)
Then we assign x to i + 1, because (i + 1) will be the length of subarray whose sum is multiple of N
In other case whenever we get a mod value, if this index is not -1, that means it is updated by some other sum value, whose index is stored at that index, we update x with this difference value, i.e. by i – modIdx[k].
After each above operation we update the minimum value of length and corresponding starting index and end index for the subarray. Finally, this gives the solution to our problem.
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Count number of permutation of an Array having no SubArray of size two or more from original Array
- Find a subarray whose sum is divisible by size of the array
- Maximum subarray size, such that all subarrays of that size have sum less than k
- Count all possible groups of size 2 or 3 that have sum as multiple of 3
- Subarray of size k with given sum
- Smallest multiple of N formed using the given set of digits
- Smallest Subarray with given GCD
- Size of The Subarray With Maximum Sum
- Kth smallest element in a subarray
- Smallest sum contiguous subarray
- Smallest subarray with sum greater than a given value
- Largest product of a subarray of size k
- Maximum circular subarray sum of size K
- Sorting possible using size 3 subarray rotation
- Smallest subarray with product divisible by k