Need some clarification for SIGSEGV error


runtime error
correct answer

there is only one difference in the above solutions is that at the 20th line, in the for loop’s termination condition, I have just applied some modifications and miracle, my solution accepted, can anyone tell how this happens internally?

vector<ll>::size_type is unsigned, so if it has to represent -1 - as it would have to if v were empty - it (i.e. v.size() - 1) would be represented as a gigantically huge positive number, and i would go out of the bounds of v.

1 Like

makes sense, thanks dude.

1 Like

This is why it is always a good practice to cast v.size() to int like int(v.size()) to avoid undefined behaviour. :slight_smile:

1 Like