I may have an easier solution. in O(n) time and O(n+k) space. where n is the size of array & k is the number we are checking the divisibility with.
Consider the array as A[n] and the number is K
- create another array SUM_TILL_NOW[n].
- for each A[i] fill SUM_TILL_NOW [i]= SUM_TILL_NOW[i-1]+A[i] %K; (SUM_TILL_NOW[0]= A[0])
- find two numbers which are equal in this new Array.
To do that create a new array CHECK[] of size K.
Iterate over the SUM_TILL_NOW array and check if CHECK[SUM_TILL_NOW[i]] set.
If not set it to i.
else CHECK[SUM_TILL_NOW[i]], i is the subset where the sum is divisible by K.
Below is a c++ function of the same.
#include
#include
using namespace std;
void printrange(int* A, int N, int K)
{
int STN[N], C[K];
memset(C, -1, K*sizeof(int));
int i;
int sum=A[0];
STN[0]= (A[0]%K);
for (i= 1; i< N; i++)
{
sum+= A[i];
STN[i]= sum%K;
}
for(i=0; i< N; i++)
{
if(C[STN[i]] == -1)
C[STN[i]] =i;
else
{
cout<< C[STN[i]]+1 <<" "<< i;
break;
}
}
}
int main()
{
int A[]= {6, 9, 2, 1, 8, 6, 2, 5};
printrange(A, sizeof(A)/sizeof(A[0]), 7);
return 0;
}