A way of initialization of the parent array

In many tutorials I’ve seen that parent array was initialized like this:

for(int i = 0; i < N; ++i) {
parent[i] = i;
size[i] = 1;
}

And then the find function was written like this:

int find(int x) {
while(x != parent[x]) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return parent[x];
}

In this video I see that parent was initialized with -1’s.
Could you please explain what is the main differences and in which situation those ways?

hello @begginner_cp

both are correct.

if we have intilaised with -1, then here in while loop it should be
while(parent[x]!=-1){
something
}

rest everthing will remain same

1 Like

Ok I got it, thanks.

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.

1 Like