Why this Code giving Runtime error on testcase 4 on codeforces

#include<bits/stdc++.h>
using namespace std;

#define ll long long

int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);

ll n;
cin >> n;

vector<ll> a(n + 1);

for (ll i = 1; i <= n; i++)
	cin >> a[i];

vector<ll> lastOcc(n + 1, 0);
vector<ll> ans(n + 1, 0);

ans[0] = 0;
double sum = 0.0;

for (ll i = 1; i <= n; i++)
{
	ans[i] = ans[i - 1] + (i - lastOcc[a[i]]);
	lastOcc[a[i]] = i;

	sum = sum + ans[i];
}

double expected = 0.0;
expected = (2 * (sum - n) + n) / (n * n * 1.0);

cout << fixed << setprecision(6) << expected << endl;

return 0;

}

Hello @devang_11912089,

Let me give you a test case where your code gives runtime error,

N = 1
array = [ 1000000 ]

Now in this line, lastOcc[a[i]] = lastOcc[1000000] => trying to access memory that never existed which gives runtime error (Size of lastOcc is 2).

ans[i] = ans[i - 1] + (i - lastOcc[a[i]]);
lastOcc[a[i]] = i;

@devang_11912089,

Instead of creating arrays of size n+1, you should make it 1000001 (1e6+1)

1 Like

@devang_11912089,

Is it working now?

Yes it’s working now

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.