## DEV Community is a community of 665,273 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Discussion on: Solution: Set Mismatch (ver. 2) InHuOfficial • Edited

Interesting, but given the constraints isn't this as simple as just looping through an ordered array until we get a number that isn't it's index + 1 and then checking if the before value is the same? As there can only ever be one digit incorrect and it must be one higher or one lower than the digit that is replaced?

Or did I miss some key part of the question as I am terrible at these sorts of things lol!

If I am correct then the beauty of this is a single loop that exits the second it finds a match so it should be computationally efficient. seanpgallivan

But you're assuming that the input array (nums) is sorted; the problem description doesn't state that. And sorting it first would make the solution O(N * log N) instead of just O(N).

It can be a bit hard to explain, but each element of the solution posted here tells us two things... but about different numbers. One number is the actual value of the element, the other is the number that is equal to the index of the element plus 1.

So if we reach the end, for example, and see that nums = 20002, then we know that the number 6 (i = 5 so i + 1 = 6) was seen twice, not the number 2. And yet we still preserved our ability to read the number 2 in this element with 20002 % 10000.

That's important because we'll be modifying the elements out of order in our first pass, and don't want to screw up our ability to properly read each number later on in the pass.

So in other words, in the first pass we're reading nums at i, but we're modifying nums at nums[i]. That's because we're treating nums very much like we would its own "seen" or "visited" array. We just don't want those two purposes for nums to impact each other, so we just... overlay another level of meaning onto the values stored in nums.

It's very much similar to using bit manipulation to combine two pieces of data into one. InHuOfficial

This is why I am rubbish at these problems, I forget that `.sort` is expensive!

I get it entirely now and thanks for taking the time to give such a detailed explanation! 