I had the following question in an interview and, in spite of the fact that I gave a working implementation, it wasn't efficient enough.
A slice of array A is any pair of integers (P, Q) such that 0 ≤ P ≤ Q
< N. A slice (P, Q) of array A is divisible by K if the number A[P] +
A[P+1] + ... + A[Q?1] + A[Q] is divisible by K.
The function I was asked to write, had to return the number of slices divisible by K. The expected time complexity was O(max(N, K)) and space complexity was O(K).
My solution was the simplest, one loop inside another and check every slice: O(n^2)
I have been thinking but I really can't figure out how can I do it in O(max(N, K)).
It may be a variant of the subset sum problem, but I don't know how to count every subarray.
EDIT: Elements in array could be negatives. Here is an example:
A = {4, 5, 0, -2, -3, 1}, K = 5
Function must return 7, because there are 7 subarrays which sums are divisible by 5
{4, 5, 0, -2, -3, 1}
{5}
{5, 0}
{5, 0, -2, -3}
{0}
{0, -2, -3}
{-2, -3}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…