educative.io

Why would the code work?

if the number set be like [2 ,2 ,2 ,2] , won’t the iteration be never stopping?


Type your question above this line.

Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/4893412715134976

Hey @Annabelle_Sun!
We use the Cyclic Sort to place the numbers on their correct index. Once we have every number in its correct place, we can iterate the array to find the index which does not have the correct number, and that index will be our missing number. In the case of [2, 2, 2, 2] 1, 3, and 4 are missing at the expected indexes.
So the output would be [1, 3, 4].
We hope Educative has inspired you to further your learning. Thank you for asking the question.

iteration will not enter the if condition if there are duplicates. therefore the algorithm will work finitely. To explain it better . Take the case of your example [2, 2, 2, 2]

Now the condition is if ( num[i] != nums[nums[i]-1]). => replace i and will find both are equal i.e 2 == 2 , therefore it would not enter if but enter else and increment i.

This really looks confusing at first. Giving better variable names would be much easier to understand.

int sendNumberToIdx = nums[currentIdx] -1 ;

then if condition will look like if (nums[currentIdx] != nums[sendNumberToIdx]). ==> This is less confusing.

@Annabelle_Sun hope this helps.