count distinct slices in an array
The solution is not correct because your algorithm is wrong.
First of all, let me show you a counter example. Let A = {2, 1, 2}
. The first iteration: base = 0
, fibot = 0
, sum += 1.
That's right. The second one: base = 0, fibot = 1
, sum += 2
. That's correct, too. The last step: fibot = 2
, check[A[fibot]] is true
, thus, base = 2
. But it should be 1
. So your code returns1 + 2 + 1 = 4
while the right answer 1 + 2 + 2 = 5
.
The right way to do it could be like this: start with L = 0
. For each R
from 0
to n - 1
, keep moving the L
to the right until the subarray contais only distinct values (you can maintain the number of occurrences of each value in an array and use the fact that A[R]
is the only element that can occur more than once).
There is one more issue with your code: the sum
variable may overflow if int
is 32-bit type on the testing platform (for instance, if all elements of A
are distinct).
As for the question WHY your algorithm is incorrect, I have no idea why it should be correct in the first place. Can you prove it? The base = fibot
assignment looks quite arbitrary to me.