Re: Microsoft Interview Questions
- From: Patricia Shanahan <pats@xxxxxxx>
- Date: Sat, 20 Jan 2007 21:38:44 GMT
stdazi@xxxxxxxxx wrote:
Patricia Shanahan wrote:stdazi@xxxxxxxxx wrote:you are completely right! i knew there was some issue with that methodThe code suggests that you are assuming zero-terminated strings. UnderQ2) What is an efficient way to determine whether a string is adamn i forgot.. another method would be to use XOR and apply it to some
permutation of another string? What is your run time?
integer for each char of the two strings (presuming that the char value
can be casted to an integer tipe...) like that :
4 int isperm(char *s1, char *s2) {
5
6 int retval = 0;
7
8 while (*s1 || *s2) {
9 retval ^= *s1 ^ *s2 ;
10 ++s1; ++s2;
11 }
12 return retval || (*s1 != *s2);
13 }
this is a O(n) algorithm where n is the lenght of the "shortest" string.
that assumption, it appears to me to test two conditions:
1. Are the two strings the same length?
2. Let X_n be the number of 1 bits in bit position n in s1, and Y_n be
the number of 1 bits in bit position n in s1. For each bit position, is
(X_n - Y_n) even?
Both conditions are true if they are permutations of each other.
However, there are many pairs of strings that are not permutations but
that would pass those tests. For example:
int main(argc,argv) int argc; char *argv[];{
printf("%d\n",isperm("AB","BA"));
printf("%d\n",isperm("AA","BB"));
}
but couldn't find a counter example. So i pasted the code in hope there
is nothing wrong with it :-)
why is the first case (AB, BA) not a permutation?
It is a permutation. The point is that I got the same return value,
zero, from isperm for both a permutation pair and a non-permutation
pair, demonstrating failure to distinguish them.
Remember there was no comment or specification to indicate how to map
the integer result to a true/false answer to the "are they
permutations of each other?" question. Zero might have implied "false".
Just obtaining the answer for a non-permutation would not have proved
much.
Patricia
.
- References:
- Microsoft Interview Questions
- From: kool_guy
- Re: Microsoft Interview Questions
- From: stdazi@xxxxxxxxx
- Re: Microsoft Interview Questions
- From: Patricia Shanahan
- Re: Microsoft Interview Questions
- From: stdazi@xxxxxxxxx
- Microsoft Interview Questions
- Prev by Date: Re: convex hulls
- Next by Date: Re: Microsoft Interview Questions
- Previous by thread: Re: Microsoft Interview Questions
- Next by thread: Re: Microsoft Interview Questions
- Index(es):
Relevant Pages
|