Below code is for finding least missing positive number and it is correctly implemented
but i have a doubt let me explain by a sample input
-4 -3 -2 1 2
It’s Correct Output should be 3
But before getting the final code my previous code was giving Output 5
which is why i added line no. 35 Because in the case when we have complete positive series which is incremented by 1 then My code doesn’t return any value
Link For code
So my question is If On simmilar cases if we have complete positive series why it is returning the value of n
int solve(int arr, int n)
sort(arr, arr + n);
int i = 0, track = 1;
while (arr[i] != 1 && i < n) // to skip -ve no.s and 0
if (i == n)
while (i < n)
if (arr[i] == track)
while (arr[i] != track && i < n) // for handling duplicates
if (arr[i] > track)
// return track;
It is a clear example of undefined behaviour. According to your program logic if there exist negative numbers in your input it comes at the end of your function control and doesn’t find anything to return, so it returns a garbage value. In this case, the garbage value is n, but it could have been any funky number.
I tried with multiple test cases and in all it was returning with the value of n.
I tested on Microsoft visual studio
Well thanks for your reply i learned about undefined behavior
Cool. If you find any particular reason why it is returning n, then do reply.
Well i don’t Know the reason, that’s why i was curious to know why it was happening
I have cleaned your code and it seems to work
I don’t know why it was returning n. I was expecting garbage value.
Well I already mentioned in the question that i have the correct solution.
I especially removed that line so that people can explain me what is happening in the output.
same here when i found that i haven’t returned any value for that case,
I was thinking why not getting compiler error’s or garbage value
I asked on stackoverflow also and you were correct that it was undefined behavior. So anything can be the output and the reason why all of the time value is n, is just mere luck.