Monday, September 25th
Find the Non-Duplicate
Given 2 arrays, where 1 array is a jumble of the other plus an extra character, find the extra character
There is a similar problem to this (which I cannot find at the moment), except with numbers where we are to find a missing number. A limit for that problem was no extra space.
Here we are allowed extra space, so finding the difference in the 2 strings is pretty straightforward. Still, we can do better
We can utilize bitwise XOR. Beginning with a char set equal to 0, we iterate through both arrays and XOR each character. Whenever the same character is XOR'd twice, it is equal to zero.
Since all characters in string 1 appear in string 2, everything will XOR to zero except for the extra character in string 2, which when XOR'd will give us the character itself, and thus the answer
With some condensing, the problem can be solved in 6 lines:
Good example to keep XOR fresh in the mind. There are a few problems where one is searching for the unique character, and bitwise manipulations are a good skill to have
Comments
Post a Comment