Subarray with distinct elements


could you please help me in optimization part? I am getting tle in 2 test cases.

hello @samardeep
why are u deleting it2.

u should delete a[i] once expansion is done.

int sumOflength(int *arr, int n) {
    unordered_set<int> s;
    int j=0, ans=0;
    for(int i=0;i<n;i++) {  // j hamara right pointer hai , i hamara left pointer hai
        while(j<n and s.find(arr[j])==s.end()) { // expand kar rahe hai jabtak distint element hai
            s.insert(arr[j]);
            j++;
        }
        ans+= ((j-i)*(j-i+1))/2;// j-i jo hai wo L hai 
        s.erase(arr[i]);//starting element ko erase kar rahe hai kyuni ab window me distinct element nahi hai
    }
    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.