Divisible Subarrays

#include
#include
using namespace std;
int main() {
int t;
cin>>t;

while(t--){
    int n;
    cin>>n;
    int a[n];
	for(int i=0;i<n;i++)
	cin>>a[i];
	int cumulative[n+1];
	cumulative[0]=0;
	for(int i=0;i<n;i++){
		cumulative[i+1]=cumulative[i]+a[i];
	}
	for(int i=0;i<n;i++){
		cumulative[i+1]=cumulative[i+1]%n;
	}        
    int ans=0;

    for(int i=0;i<=n;i++)
    cout<<endl;
    sort(cumulative+1,cumulative+n+1);
    

    for(int i=0;i<n+1;i++){
        int count=upper_bound(cumulative,cumulative+n+1,cumulative[i])-lower_bound(cumulative,cumulative+n+1,cumulative[i]);
        i=upper_bound(cumulative,cumulative+n+1,cumulative[i])-cumulative-1;
        ans=ans+((count*(count-1))/2);
    }
    cout<<ans<<endl;
}

return 0;

}
Cab you go through the code and see why its showing TLE for some cases and whats the work around?

@duttrohan0302 Hey you can make an array of size n, that will act as frequency array, and will give you count in O(1), now as all the number are modulo n, they will be less than one, so their frequency can be counted using array of size n, Just take care of negative elements.
Refer to this code.


If this resolves your doubt mark it as resolved.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.