solution for problem 1 :
let the given vector and x be:
vector<int> v={3,7,27,23};
int x=10;
map<int,int> m;
int cnt=0;
int ans=0;
for(int i=0;i<v.size();i++){
if(v[i]%x==0){
cnt++;
}
else{
int rem=v[i]%x;
int check=x-rem;
if(m[check]){
ans+=m[check];
}
}
m[v[i]%x]++;
}
int val=((cnt*(cnt-1))/2);
cout<<val+ans<<endl;
Question 1 solution
// C++ Program to count pairs
// whose sum divisible by 'K'
#include <bits/stdc++.h>
using namespace std;
// Program to count pairs whose sum divisible
// by 'K'
int countKdivPairs(int A[], int n, int K)
{
// Create a frequency array to count
// occurrences of all remainders when
// divided by K
int freq[K] = { 0 };
// Count occurrences of all remainders
for (int i = 0; i < n; i++)
++freq[A[i] % K];
// If both pairs are divisible by 'K'
int sum = freq[0] * (freq[0] - 1) / 2;
// count for all i and (k-i)
// freq pairs
for (int i = 1; i <= K / 2 && i != (K - i); i++)
sum += freq[i] * freq[K - i];
// If K is even
if (K % 2 == 0)
sum += (freq[K / 2] * (freq[K / 2] - 1) / 2);
return sum;
}
// Driver code
int main()
{
int A[] = { 2, 2, 1, 7, 5, 3 };
int n = sizeof(A) / sizeof(A[0]);
int K = 4;
cout << countKdivPairs(A, n, K);
return 0;
}
Q2->
int avg(vector<int> &arr,int k){
int n=arr.size();
int result = 0, curSum = 0;
unordered_map<int, int> mp;
for (int i = 0; i < n; i++) {
curSum += (arr[i] - k);
if (curSum == 0)result++;
if (mp.find(curSum) != mp.end())result += mp[curSum];
mp[curSum]++;
}
return result;
}
vector<int> solve(vector<int> &arr){
vector<int> res;
for(int i=1;i<=arr.size();i++){
res.push_back(avg(arr,i));
}
return res;
}