educative.io

Coud we just do nums[i]- 1 != i instead of nums[i] != nums[nums[i] - 1]?

what’s the diff of these two, aren’t we just check whether the current index matches the number in that index minus 1?

4 Likes

nums[i] - 1 != i works, and I prefer it because it makes it obvious what we are checking. The provided solution does not seem to have any advantage over this simpler check.

Edit: note that the above would not work if there are duplicates in the array. So probably the author just wanted to maintain the same implementation across multiple problems, to avoid confusion.

5 Likes

Yes but having duplicates doesn’t necessarily mean that the author’s approach will sort the array correctly.

Take the following input for example [4, 5, 6, 4, 3, 2, 1]

This would return 1, 2, 3, 4, 5, 6, 4 which is not correctly sorted.