Sub array with distinct element(TLE is coming and i m confused why this is wrong )

#include
#include<unordered_set>
using namespace std;
int main() {
int n;
cin>>n;
int arr[n];

for(int i=0;i<n;i++){
	cin>>arr[i];
}


int j=0;
int sum=0;
for(int i=0;i<n;i++){
	j=i;
	unordered_set<int> s;
	if(s.empty()){
		s.insert(arr[i]);
	}
	
	while(j<n && s.find(arr[i])!=s.end()){

		s.insert(arr[i]);
		j++;
	}

	int size=j-i;
	sum=sum+(size*(size+1)/2);

}
cout<<sum<<endl;
return 0;

}

@amanpunetha please explain your approach a little, because there is some mistake in maintaining the elements in set.

@amanpunetha
The problem is with you j pointer here, you need to declare it outside the for loop, also set outside the loop.
Just keep iterating with fixed i and moving j++ till some same element is found.
I will suggest you to dry run.

If you are not able to solve it and want to correct your code, let me know.

thank you soo much i found my mistake

1 Like