Bit Manipulation and XOR - c++

I have an Question regarding bit manipulation in Algorithms.
Given an array of integers, every element in array appears thrice except for one element which occurs only once. Find that element which appear only once.
Example:
Input : [1, 2, 4, 3, 3, 2, 2, 3, 1, 1]
Output : 4
I came across solution using XOR but I am not able to understand it. Below is solution:
int singleNumber(vector<int> A) {
int first = 0;
int second = 0;
for(auto n:A){
first = (first ^ n) & ~second;
second = (second ^ n) & ~first;
}
return first;
}
Can someone explain how below 2 lines of code works?
first = (first ^ n) & ~second;
second = (second ^ n) & ~first;
[Edited]
I had included cout<<first<<" "<<second<<endl; for every iteration in loop but it is showing following output which I am not able to understand. How this lead to solution?
1 0
3 0
7 0
4 3
4 0
6 0
4 2
5 0
4 1
4 0

What this code does is count the occurrences of each bit, in parallel, mod 3.
The nth bit of first and the nth bit of second together make this counter.
Watch what happens when I write a bit of first and second together and then incorporate a bit from the new number. Here are all the possibilities:
secondfirst 00 01 10 00 01 10
new bit 0 0 0 1 1 1
first=first^new &~second 0 1 0 1 0 0
+ sec=sec^new & ~first 00 01 10 01 10 00
As you can see, the two bits are left unchanged when the corresponding bit in the new number is 0. When the new bit is 1, though, they go through a cycle, returning back to 00 every 3 steps. If the number of 1s is 3n+1, we're left with a 1 bit in first

Related

Intuition behind working with `k` to find the kth-symbol in the grammar

I took part in a coding contest wherein I encountered the following question:
On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.)
While solving the question, I solved it like a level-order traversal of a tree, trying to form the new string at each level. Unfortunately, it timed-out. I then tried to think along the terms of caching the results, etc. with no luck.
One of the highly upvoted solutions is like this:
class Solution {
public:
int kthGrammar(int N, int K) {
if (N == 1) return 0;
if (K % 2 == 0) return (kthGrammar(N - 1, K / 2) == 0) ? 1 : 0;
else return (kthGrammar(N - 1, (K + 1) / 2) == 0) ? 0 : 1;
}
};
My question is simple - what is the intuition behind working with the value of K (especially, the parities of K)? (I hope to be able to identify such questions when I encounter them in future).
Thanks.
Look at the sequence recursively. In generating a new row, the first half is identical to the process you used to get the previous row, so that part of the expansion is already done. The second half is merely the same sequence inverted (0 for 1, 1 for 0). This is one classic way to generate a parity map: flip all the bits and append, representing adding a 1 to the start of each binary number. Thinking of expanding the sequence 0-3 to 0-7, we start with
00 => 0
01 => 1
10 => 1
11 => 0
We now replicate the 2-digit sequence twice: first with a leading 0, which preserves the original parity; second with a leading 1, which inverts the parity.
000 => 0
001 => 1
010 => 1
011 => 0
100 => 1
101 => 0
110 => 0
111 => 1
Is that an intuition that works for you?
Just for fun, as a different way to solve this, consider that the nth row (0-indexed) has 2^n elements in it, and a determination as to the value of the kth (0-indexed) element can be made soley according to the parity of how many bits are set in k.
The check for parity in the code you posted is just to make the division by two correct, there's no advanced math or mystery hiding here :) Since the pattern is akin to a tree, where the pattern size multiplies by two for each added row, correctly dividing points to the element's parent. The indexes in this question are said to be "1-indexed;" if the index is 2, dividing by two yields the parent index (1) in the row before; and if the index is 1, dividing (1+1) by two yields that same parent index. I'll leave it to the reader to generalize that to ks parity. After finding the parent, the code follows the rule stated in the question: if the parent is 0, the left-child must be 0 and right-child 1, and vice versa.
0
0 1
0 1 1 0
0 1 1 0 1 0 0 1
0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0
a a b a b b a
0 01 0110 01101001 0110100110010110
a b b a b a a b
0110100110010110 1001011001101001

Why is x^0 = x?

I have a very simple question.
Why is a number when XOR'ed with 0 gives the number itself.
Can someone please give the proof using an example.
Lets say I have the number 5
5^0==>
I think the answer should be just the last bit of 5 XOR'ed with 0, but the answer is still 5.
0 is false, and 1 is true.
As per the definition, XOR operation A XOR B is "A or B, but not, A and B". So, since B is false, so the result will be A.
Also, XOR truth table shows that it outputs true whenever the inputs differ:
Input Output
A B XOR Result
0 0 0
0 1 1
1 0 1
1 1 0
As you can see, whatever be the value of A, if it is XORed with 0, the result is the bit itself.
So, as you say:
5 = 101, 0 = 000
When performing XOR operation on the individual bits:
101
000
----
101 = 5.
Hence, the result of X^0 is X itself.
What is there that you did not understand. Please read about XOR
00000101 // = 5
00000000 // = 0
--------
00000101 // = 5
Bit-wise operations operates on set of bits in number - not just on last bit.
So if you perform some bit-wise operation on 32-bit integer, then all 32 bits are affected. So integer 5 is 0.....0000101 (32 bits). If you need just the resulting last bit after xor operation apply binary AND with 1:
<script>
console.log("%i\n",(5^0)&1);
console.log("%i\n",(6^0)&1);
</script>

Counting ways of breaking up a string of digits into numbers under 26

Given a string of digits, I wish to find the number of ways of breaking up the string into individual numbers so that each number is under 26.
For example, "8888888" can only be broken up as "8 8 8 8 8 8 8". Whereas "1234567" can be broken up as "1 2 3 4 5 6 7", "12 3 4 5 6 7" and "1 23 4 5 6 7".
I'd like both a recurrence relation for the solution, and some code that uses dynamic programming.
This is what I've got so far. It only covers the base cases which are a empty string should return 1 a string of one digit should return 1 and a string of all numbers larger than 2 should return 1.
int countPerms(vector<int> number, int currentPermCount)
{
vector< vector<int> > permsOfNumber;
vector<int> working;
int totalPerms=0, size=number.size();
bool areAllOverTwo=true, forLoop = true;
if (number.size() <=1)
{
//TODO: print out permetations
return 1;
}
for (int i = 0; i < number.size()-1; i++) //minus one here because we dont care what the last digit is if all of them before it are over 2 then there is only one way to decode them
{
if (number.at(i) <= 2)
{
areAllOverTwo = false;
}
}
if (areAllOverTwo) //if all the nubmers are over 2 then there is only one possable combination 3456676546 has only one combination.
{
permsOfNumber.push_back(number);
//TODO: write function to print out the permetions
return 1;
}
do
{
//TODO find all the peremtions here
} while (forLoop);
return totalPerms;
}
Assuming you either don't have zeros, or you disallow numbers with leading zeros), the recurrence relations are:
N(1aS) = N(S) + N(aS)
N(2aS) = N(S) + N(aS) if a < 6.
N(a) = 1
N(aS) = N(S) otherwise
Here, a refers to a single digit, and S to a number. The first line of the recurrence relation says that if your string starts with a 1, then you can either have it on its own, or join it with the next digit. The second line says that if you start with a 2 you can either have it on its own, or join it with the next digit assuming that gives a number less than 26. The third line is the termination condition: when you're down to 1 digit, the result is 1. The final line says if you haven't been able to match one of the previous rules, then the first digit can't be joined to the second, so it must stand on its own.
The recurrence relations can be implemented fairly directly as an iterative dynamic programming solution. Here's code in Python, but it's easy to translate into other languages.
def N(S):
a1, a2 = 1, 1
for i in xrange(len(S) - 2, -1, -1):
if S[i] == '1' or S[i] == '2' and S[i+1] < '6':
a1, a2 = a1 + a2, a1
else:
a1, a2 = a1, a1
return a1
print N('88888888')
print N('12345678')
Output:
1
3
An interesting observation is that N('1' * n) is the n+1'st fibonacci number:
for i in xrange(1, 20):
print i, N('1' * i)
Output:
1 1
2 2
3 3
4 5
5 8
6 13
7 21
8 34
9 55
If I understand correctly, there are only 25 possibilities. My first crack at this would be to initialize an array of 25 ints all to zero and when I find a number less than 25, set that index to 1. Then I would count up all the 1's in the array when I was finished looking at the string.
What do you mean by recurrence? If you're looking for a recursive function, you would need to find a good way to break the string of numbers down recursively. I'm not sure that's the best approach here. I would just go through digit by digit and as you said if the digit is 2 or less, then store it and test appending the next digit... i.e. 10*digit + next. I hope that helped! Good luck.
Another way to think about it is that, after the initial single digit possibility, for every sequence of contiguous possible pairs of digits (e.g., 111 or 12223) of length n we multiply the result by:
1 + sum, i=1 to floor (n/2), of (n-i) choose i
For example, with a sequence of 11111, we can have
i=1, 1 1 1 11 => 5 - 1 = 4 choose 1 (possibilities with one pair)
i=2, 1 11 11 => 5 - 2 = 3 choose 2 (possibilities with two pairs)
This seems directly related to Wikipedia's description of Fibonacci numbers' "Use in Mathematics," for example, in counting "the number of compositions of 1s and 2s that sum to a given total n" (http://en.wikipedia.org/wiki/Fibonacci_number).
Using the combinatorial method (or other fast Fibonacci's) could be suitable for strings with very long sequences.

Why does "number & (~(1 << 3))" not work for 0's?

I'm writing a program that exchanges the values of the bits on positions 3, 4 and 5 with bits on positions 24, 25 and 26 of a given 32-bit unsigned integer.
So lets say I use the number 15 and I want to turn the 4th bit into a 0, I'd use...
int number = 15
int newnumber = number & (~(1 << 3));
// output is 7
This makes sense because I'm exchanging the 4th bit from 1 to 0 so 15(1111) becomes 7(0111).
However this wont work the other way round (change a 0 to a 1), Now I know how to achieve exchanging a 0 to a 1 via a different method, but I really want to understand the code in this method.
So why wont it work?
The truth table for x AND y is:
x y Output
-----------
0 0 0
0 1 0
1 0 0
1 1 1
In other words, the output/result will only be 1 if both inputs are 1, which means that you cannot change a bit from 0 to 1 through a bitwise AND. Use a bitwise OR for that (e.g. int newnumber = number | (1 << 3);)
To summarize:
Use & ~(1 << n) to clear bit n.
Use | (1 << n) to set bit n.
To set the fourth bit to 0, you AND it with ~(1 << 3) which is the negation of 1000, or 0111.
By the same reasoning, you can set it to 1 by ORing with 1000.
To toggle it, XOR with 1000.

High efficient algorithm for picking up number from array

Here is the problem:
There are 2*N+1 integers in one array, and there are N pair int numbers, i,e, two 1, or two 3 etc,so there is only one int number , which has no pair.
The question is how to find this number with high efficient algorithm.
Thanks for any clues or comments.
Ok, Ok, here's an explanation of my comment. :-/
missingNum = 0
for each value in list
missingNum = missingNum ^ value //^ = xor
next
print(missingNum)
That's a linear algorithm, O(n).
So what's happening here? Say, we have [2,1,3,1,2], for those familiar with XOR operator, know that 1 ^ 1 = 0, 0 ^ 0 = 0, and 1 ^ 0 = 1, 0 ^ 1 = 1 (remember there's no carry)
So essentially, when we XOR a sequence of bits (100110111), and it has even numbers of 1, each will XOR themselves to zero...if the number of 1's are odd, the XOR yields a 1
So in our example, starting from lsb
2 : 0010
1 : 0001
3 : 0011
1 : 0001
2 : 0010
lsb bit: 0 ^ 1 ^ 1 ^ 1 ^ 0 : 1
2nd bit: 1 ^ 0 ^ 1 ^ 0 ^ 1 : 1
3rd bit: 0 ^ 0 ^ 0 ^ 0 ^ 0 : 0
4th bit: 0 ^ 0 ^ 0 ^ 0 ^ 0 : 0
So our missing number is
0011 = 3
You can find more universal answer in this question. If you assume n=2, m=1 you'll get what you want.
But, as st0le said, in your case XOR should be enough.
If I understand the question correctly, you've got an array containing an odd number of integer values, consisting of a number of integers that appear twice plus one integer that appears only once. For example, the array might look like this:
[3, 41, 6, 6, 41]
where 6 and 41 are both repeated and 3 is unique.
It would be good to know if there are any other constraints. For example:
Is the array sorted? (If so, this is a simple problem to solve in O(N) time with no requirement for temporary storage.)
Can the unpaired integer be the same as an integer in a pair? e.g. is [1, 2, 2, 2, 1] a valid input, being a pair of 1s, a pair of 2s and an unpaired 2?
Assuming the array isn't sorted, here's one solution, expressed in pseudocode, which runs in O(N) time and requires at most around half the storage space again of the original array.
SEEN = []
for N in ARRAY:
if N in SEEN:
remove N from SEEN
else:
add N to SEEN
if size of SEEN != 1:
error - ARRAY doesn't contain exactly 1 un-paired value
else:
answer = SEEN[0]
Here's a sample implementation using an NSMutableDictionary to store seen values, assuming that the source array is a plain C array.
#import <Foundation/Foundation.h>
int main(int argc, char argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int array[9] = {3, 4, 5, 6, 7, 6, 5, 4, 3};
NSMutableDictionary *d = [NSMutableDictionary dictionaryWithCapacity:16];
for (int i = 0; i < sizeof(array)/sizeof(int); i++) {
NSNumber *num = [NSNumber numberWithInt:array[i]];
if ([d objectForKey:num]) {
[d removeObjectForKey:num];
} else {
[d setObject:[NSNull null] forKey:num];
}
}
if ([d count] == 1) {
NSLog(#"Unpaired number: %i", [[[d keyEnumerator] nextObject] intValue]);
} else {
NSLog(#"Error: Expected 1 unpaired number, found %u", [d count]);
}
[pool release];
return 1;
}
And here it is running:
$ gcc -lobjc -framework Foundation -std=c99 demo.m ; ./a.out
2010-12-25 11:23:21.426 a.out[17544:903] Unpaired number: 7