High efficient algorithm for picking up number from array - c++

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

Related

Bit Manipulation and XOR

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

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

Can we find if 0 occurs odd number of times in an array using bit manipulation

I know that, XORing all elements of an integer array which contains all of its elements except 1 element occuring even number of times gives the number that occurs odd number of times.
Example
{ 1, 1, 2, 2, 3 }
1 ^ 1 ^ 2 ^ 2 ^ 3 = 3;
^ is XOR
What if the number occuring odd number of times is 0?
{ 1, 1, 2, 2, 0 }
1 ^ 1 ^ 2 ^ 2 ^ 0 = 0 // Both give
1 ^ 1 ^ 2 ^ 2 = 0 // same answer
How to confirm that 0 is occuring odd number of times
PS : Prefer the answer code to be in C/C++
Let's call N, the number of elements in your array:
If (N is even) AND (XORing all elements ==0) -> All the elements occur even number of times
if (N is odd) AND (XORing all elements ==0) -> You single element is zero.
This is how to check if an integer is even or odd in C / C++

Ordering an array based on 2D array of relations (higher, lower, doesn't matter)

I have been stuck with this problem for two days and I still can't get it right.
Basically, I have a 2D array with relations between certain numbers (in given range):
0 = the order doesn't matter
1 = the first number (number in left column) should be first
2 = the second number (number in upper row) should be first
So, I have some 2D array, for example this:
0 1 2 3 4 5 6
0 0 0 1 0 0 0 2
1 0 0 2 0 0 0 0
2 2 1 0 0 1 0 0
3 0 0 0 0 0 0 0
4 0 0 2 0 0 0 0
5 0 0 0 0 0 0 0
6 1 0 0 0 0 0 0
And my goal is to create a new array of given numbers (0 - 6) in such a way that it is following the rules from the 2D array (e.g. 0 is before 2 but it is after 6). I probably also have to check if such array exists and then create the array. And get something like this:
6 0 2 1 4 5
My Code
(It doesn't really matter, but I prefer c++)
So far I tried to start with ordered array 0123456 and then swap elements according to the table (but that obviously can't work). I also tried inserting the number in front of the other number according to the table, but it doesn't seem to work either.
// My code example
// I have:
// relArr[n][n] - array of relations
// resArr = {1, 2, ... , n} - result array
for (int i = 0; i < n; i++) {
for (int x = 0; x < n; x++) {
if (relArr[i][x] == 1) {
// Finding indexes of first (i) and second (x) number
int iI = 0;
int iX = 0;
while (resArr[iX] != x)
iX++;
while (resArr[iI] != i)
iI++;
// Placing the (i) before (x) and shifting array
int tmp, insert = iX+1;
if (iX < iI) {
tmp = resArr[iX];
resArr[iX] = resArr[iI];
while (insert < iI+1) {
int tt = resArr[insert];
resArr[insert] = tmp;
tmp = tt;
insert++;
}
}
} else if (relArr[i][x] == 2) {
int iI = 0;
int iX = 0;
while (resArr[iX] != x)
iX++;
while (resArr[iI] != i)
iI++;
int tmp, insert = iX-1;
if (iX > iI) {
tmp = resArr[iX];
resArr[iX] = resArr[iI];
while (insert > iI-1) {
int tt = resArr[insert];
resArr[insert] = tmp;
tmp = tt;
insert--;
}
}
}
}
}
I probably miss correct way how to check whether or not it is possible to create the array. Feel free to use vectors if you prefer them.
Thanks in advance for your help.
You seem to be re-ordering the output at the same time as you're reading the input. I think you should parse the input into a set of rules, process the rules a bit, then re-order the output at the end.
What are the constraints of the problem? If the input says that 0 goes before 1:
| 0 1
--+----
0 | 1
1 |
does it also guarantee that it will say that 1 comes after 0?
| 0 1
--+----
0 |
1 | 2
If so you can forget about the 2s and look only at the 1s:
| 0 1 2 3 4 5 6
--+--------------
0 | 1
1 |
2 | 1 1
3 |
4 |
5 |
6 | 1
From reading the input I would store a list of rules. I'd use std::vector<std::pair<int,int>> for this. It has the nice feature that yourPair.first comes before yourPair.second :)
0 before 2
2 before 1
2 before 4
6 before 0
You can discard any rules where the second value is never the first value of a different rule.
0 before 2
6 before 0
This list would then need to be sorted so that "... before x" and "x before ..." are guaranteed to be in that order.
6 before 0
0 before 2
Then move 6, 0, and 2 to the front of the list 0123456, giving you 6021345.
Does that help?
Thanks for the suggestion.
As suggested, only ones 1 are important in 2D array. I used them to create vector of directed edges and then I implemented Topological Sort. I decide to use this Topological Sorting Algorithm. It is basically Topological Sort, but it also checks for the cycle.
This successfully solved my problem.

How to find the number of sequences of zeros and ones without "111" [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a problem:
I have a N (N <= 40). N is a length of sequence of zeroz and ones. How to find the number of sequences of zeros and ones in which there are no three "1" together?
Example:
N = 3, answer = 7
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
Here's a solution using a recursive function :
(PHP code here, but it's really simple)
$seq = '';
function tree ($node, $flag, $seq)
{
if ($flag == 3) { return 0; }
if ($node == 0) { echo $seq, ' '; return 0;}
$seq1 = $seq.'1';
$seq2 = $seq.'0';
tree($node-1, $flag+1, $seq1);
tree($node-1, 0, $seq2);
}
tree(8, 0, $seq);
I use a tree to go through all the possible sequences, and a flag to check how many 1 in a row.
If there is two 1 in a row, then the flag reaches 3, and the function is stopped for this branch.
If we reach a leaf of the tree (ie. $node = 0), then the sequence is displayed, and the function ends.
Else, the function explores the two sub-trees starting from the current node.
void tree ( int node, int flag, std::string seq)
{
std::string seq1 = seq;
std::string seq2 = seq;
if(flag ==3) { return; }
if(node ==0) { printf("%s\n",seq.c_str()); return;}
seq1 += '1';
seq2 += '0';
tree(node-1, flag+1, seq1);
tree(node-1, 0, seq2);
}
You can write a grammar for the (non-empty) strings of this language. It's designed so that each string appears exactly once.
S := 0 | 1 | 11 | 10 | 110 | 0S | 10S | 110S
Let a_i be the total number of strings of length i in S.
First, look at the number of strings of length 1 on both sides of the grammar rule. There's a_1 in S by definition which deals with the left-hand-side.
a_1 = 2
For a_2, on the right-hand-side we immediately get two strings of length 2 (11 and 10), plus another two from the 0S rule (00 and 01). This gives us:
a_2 = 2 + a_1 = 4
Similarly, for a_3, we get:
a_3 = 1 + a_2 + a_1 = 7
(So far so good, we've got the right solution 7 for the case where the strings are length three).
For i > 3, consider the number of strings of length i on both sides.
a_i = a_{i-1} + a_{i-2} + a_{i-3}
Now we've got a recurrence we can use. A quick check for a_4...
a_4 = a_1 + a_2 + a_3 = 2 + 4 + 7 = 13.
There's 16 strings of length 4 and three containing 111: 1110, 0111, 1111. So 13 looks right!
Here's some code in Python for the general case, using this recurrence.
def strings_without_111(n):
if n == 0: return 1
a = [2, 4, 7]
for _ in xrange(n - 1):
a = [a[1], a[2], a[0] + a[1] + a[2]]
return a[0]
This is a dp problem. I will explain the solution in a way so that it is easy to modify it to count the number of sequences having no sequence a0a1a2 in them(where ai is arbitrary binary value).
I will use 4 helper variables each counting the sequence up to a given length that are valid and end with 00, 01, 10, and 11 respectively. Name those c00, c01, c10, c11. It is pretty obvious that for length N = 2, those numbers are all 1:
int c00 = 1;
int c01 = 1;
int c10 = 1;
int c11 = 1;
Now assuming we have counted the sequences up to a given length k we count the sequences in the four groups for length k + 1 in the following manner:
int new_c00 = c10 + c00;
int new_c01 = c10 + c00;
int new_c10 = c01 + c11;
int new_c11 = c01;
The logic above is pretty simple - if we append a 0 to either a sequence of length k ending at 0 0 or ending at 1 0 we end up with a new sequence of length k + 1 and ending with 0 0 and so on for the other equations above.
Note that c11 is not added to the number of sequences ending with 1 1 and with length k + 1. That is because if we append 1 to a sequence ending with 1 1 we will end up with an invalid sequence( ending at 1 1 1).
Here is a complete solution for your case:
int c00 = 1;
int c01 = 1;
int c10 = 1;
int c11 = 1;
for (int i = 0; i < n - 2; ++i) {
int new_c00 = c10 + c00;
int new_c01 = c10 + c00;
int new_c10 = c01 + c11;
int new_c11 = c01;
c00 = new_c00;
c01 = new_c01;
c10 = new_c10;
c11 = new_c11;
}
// total valid sequences of length n
int result = c00 + c01 + c10 + c11;
cout << result << endl;
Also you will have to take special care for the case when N < 2, because the above solution does not handle that correctly.
To find a number of all possible sequences for N bits are easy. It is 2^N.
To find all sequences contains 111 a bit harder.
Assume N=3 then Count = 1
111
Assume N=4 then Count = 3
0111
1110
1111
Assume N=5 then Count = 8
11100
11101
11110
11111
01110
01111
00111
10111
If you write simple simulation program it yields 1 3 8 20 47 107 ...
Subtract 2^n - count(n) = 2 4 7 13 24 44 81 149...
Google it and it gives OEIS sequence, known as tribonacci numbers. Solved by simple recurrent equation:
a(n) = a(n - 1) + a(n - 2) + a(n - 3)