sir/mam,
please check my code it failed 2 test case only 1 is passed.
Subarray with distinct element
what is ur approach ?? I am unable to get it from the code
The solution is based on the fact that if we know all elements in a subarray arr[i…j] are distinct, sum of all lengths of distinct element subarrays in this subarray is ((j-i) * (j-i+1))/2 .
How? the possible lengths of subarrays are 1, 2, 3,……, j – i +1. So, the sum will be ((j – i ) * (j – i +1))/2.
We first find largest subarray (with distinct elements) starting from first element. We count sum of lengths in this subarray using above formula. For finding next subarray of the distinct element, we increment starting point, i and ending point, j unless (i+1, j) are distinct. If not possible, then we increment i again and move forward the same way.
int sumOflength(int *arr, int n) {
unordered_set<int> s;
int j=0, ans=0;
for(int i=0;i<n;i++) {
while(j<n and s.find(arr[j])==s.end()) {
s.insert(arr[j]);
j++;
}
ans+= ((j-i)*(j-i+1))/2;
s.erase(arr[i]);
}
return ans;
}
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.
Hello @chhavibansal, i found ur approach very good, but i think ur formula to count total lengths for subarray of length n is wrong, according to ur approach ur summing up n,n-1,n-2,… BUT, here we have 1 array of length n, 2 arrays of length n-1, 3 of n-2 and so on… Please correct if I am wrong. Thank you.