Check subarray with sum zero

in the solution, it is implemented by storing prefix sum values in set and checking for 0 or duplicate.

snippet:

for(i=0;i<n;i++0{
prefix += arr[i]
if( prefix ==0 or s.find(prefix) != s.end() )
return true;
else
s.insert(prefix);
}

my question:
in the first iteration of the loop, set would be empty then how does s.find() work in that case?
what is s.end() for an empty set?
shouldn’t we insert the prefix before the if condition?

@rjra2611
if the required element is not found in the set, the set::find() function returns s.end() ie the end iterator to that set. Now to your second question, I think that you believe that end iterator refers to the last element of the set. But actually it refers to a pointer AFTER the last element of the set. So end is still there for an empty set as well.

1 Like

Hi @rjra2611 please mark your doubt as resolved if you are satisfied

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.