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.
- Given an array A and a number x, check for pair in A with sum as x
- Largest Sum Contiguous Subarray
- Search an element in a sorted and rotated array
- Merge an array of size n into another array of size m+n
- Median of two sorted arrays of same size
- k largest(or smallest) elements in an array | added Min Heap method
- Program for array rotation
- Write a program to reverse an array or string
- Reversal algorithm for array rotation
- Block swap algorithm for array rotation
- Leaders in an array
- Count Inversions in an array | Set 1 (Using Merge Sort)
- Find the smallest and second smallest elements in an array
- Maximum and minimum of an array using minimum number of comparisons
- Check for Majority Element in a sorted array