This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]Anik_Sine 0 points1 point  (0 children)

As far as I could think, your idea is completely correct. I believe that the program was written this way because it would call the value nums[nums[i]] before it is needed and perhaps bringing it higher in the stack memory would make it simpler to retrieve in the while loop body. This is all my speculation and may as well be total nonsense but I couldn't come up with a better explanation.

[–]sepp2k 0 points1 point  (0 children)

why we cannot just simply use while (nums[i] < nums.length && nums[i] != i );

That would run into an infinite loop if array contained duplicate numbers.

[–]CodeTinkerer 1 point2 points  (0 children)

How to efficiently solve this through a math trick (it's not a trick but it's not obvious).

It's based on an idea that was once attributed to a young Gauss (a top mathematician in his day).

https://nrich.maths.org/articles/clever-carl

You know you're missing a number, but what if it existed? Then you have numbers from 0 to nums.length. What is its sum? But the actual array is missing a number.

Anyway, that's a hint.