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

Extra bubblegum, shared by Crookesmoor via Wikipedia under the Creative Commons Attribution-Share Alike 4.0 International license.  No changes made.

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:

    char findTheDifference(string s, string t) {
char res=0;
for(int i=0; i<s.size(); i++) {
res^=s[i];
res^=t[i];
}
return res^=t[t.size()-1];
}

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

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th