Showing posts with label prefix tree. Show all posts
Showing posts with label prefix tree. Show all posts

Jan 3, 2009

Give n 32bit numbers which are all unsigned integers, then find the two numbers that can get the maximum value after their XOR. e.g. for these numbers

Give n 32bit numbers which are all unsigned integers, then find the two numbers that can get the maximum value after their XOR.
e.g.
for these numbers: 1, 2, 3, 4, 0xFFFFFFFE,
we should return 1 and 0xFFFFFFFE whose XOR result is the max.
please give a algorithm with time complexity <= nlgn, O(n)would be better.
I think this can be done in O(n).
I have a two-pass algorithm:

1. The first pass builds a binary tree.
. The tree has n leaves corresponding to the n given numbers.
. Each leaf has a depth of 32.
. When you add a leaf, you start from the MSB, if 0 go left, if 1 go right.
2. In the second pass, for each number x, bit complement (m=~x) it first, and then find the best "match" of m in the tree.
The "match" looks like the following:

unsigned long BestMatch(unsigned long m, node * pRoot)
{
unsigned long match = 0;
for (int i=31; i>=0; i--)
{
match <<= 1;
BYTE bit = (m>>i)&0x01;
if (bit)
{
if (p->right)
{
p = p->right;
match ++;
}
else
{
p = p->left;
}
}
else
{
if (p->left)
{
p = p->left;
match ++;
}
else
{
p = p->right;
}
}
}
return match;
}

Dec 24, 2008

Create an efficient (time and memory wise) for the following:

Create an efficient (time and memory wise) for the following:
You have a dictionary of names of phone numbers. As a user is searching for a name it should show all possible combinations.
For example. As user types 'D' it should show all names beginning with D. And then when user types 'a', it should show all names beginning 'Da' etc. Something like Google sense does. So at each point of time show end users the possible combinations.
Part II. The string could be random in nature and user need not begin at the start. For example, in the name Daniel, the user can give string 'nie' and the algorithm should show all names in the dictionary with substring 'nie' which of course will include 'Daniel' and many others. You have to design a memory and time inexpensive operation.

For the first problem, a prefix tree is the most optimal solution.
For the second problem, a suffix tree might be what you need.