educative.io

If (nums[i] != nums[nums[i] - 1]) Having trouble understanding this

Having trouble understanding this if statement
if (nums[i] != nums[nums[i] - 1])

Also, if numbers are missing, how can we put numbers at their correct indices as some of them will never be correct.

Please explain.


Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Find all Missing Numbers (easy) - Grokking the Coding Interview: Patterns for Coding Questions

Hi @bee1, Thanks for reaching out.

Your concern is proper in the case that you draw. But in our current lesson, the established problem came up with the pre-requisite that each array index contain a value from 1 to N. So, the case you are discussing is excluded from our problem statement.

The problem statement assumes we must have a value on each index (as shown in the image above).

Happy Coding :keyboard: :grinning:

1 Like

Did’nt really understand your reply.
Its quite clear in the problem statement what the word missing means and I was referring to it in the same context.
If there are duplicates in the array then some of the values must be missing between 1 to N.
So for example if range is 1-6 and 3 appears twice
2,1,3,3,4,6
then number 5 is missing because 3 is occupying 5’s position.

So how is this statement ever going to be false?
if (nums[i] != nums[nums[i] - 1])

can someone also explain the meaning of above if check


Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Find all Missing Numbers (easy) - Grokking the Coding Interview: Patterns for Coding Questions


Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Find all Missing Numbers (easy) - Grokking the Coding Interview: Patterns for Coding Questions

This if statement is actually checking the value position on the same index number i , for example, 2,1,3,3,4,6. As two is on zero indexes, so num[0] ! = num[num[0]-1] is true. In this case, we will swap both the values so two moves on the second index. Check the swap after if.
Screenshot 2022-09-16 at 11.21.15 AM

What’s happening here? After executing the while loop in which if is placed, all the indices in vector findnumber contain the same values equal to the index number. But all the indices containing nothing are missing values.

The algorithm will be more understandable if you also see the code for finding the missing element.


here if ( nums[i] != i +1) check existence of same value, i+1 is used for index equivalence (as starts from 0).

1 Like

thx.

It would help a great deal if you rename i and j to currentIndex and correctIndex respectively.


Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Find all Missing Numbers (easy) - Grokking the Coding Interview: Patterns for Coding Questions

Thanks for the suggestion. No doubt, it can increase readability.

1 Like