Google Interview Question
1,230 Interview Reviews |
Back to all Google Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Engineering at Google:
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (4)
1. sorting and strcmp is straightforward and no extra memory, but n log n.
2. not too bad for memory. O(n)
3. could get nasty with super long strings. O(n)
Helpful Answer?
Yes |
No
Inappropriate?
Helpful Answer?
Yes |
No
Inappropriate?
boolean areAnagrams?( String s1, String s2)
{
int[] frequencies = new int[128]; //assuming ascii. make a hash table for unicode
for( int i = 0; i < frequencies.length; i++)
{
frequencies[ i ] = 0;
}
for(int i = 0; i < s1.length(); i++)
{
frequencies[ (int)s1.charAt(i) ]++;
}//now we have an int array corresponding to letter frequencies
for(int i = 0; i < s2.length(); i++)
{
frequencies[ (int)s2.charAt(i) ]--;
}//now, if they are anagrams, all will be zero
for(int = 0; i < s1.length(); i++)
{
if( frequencies[ (int)s1.charAt(i) ] )
{
return false;
}
}
return true;
}
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up
1 of 1 people found this helpful
by srikanth:
1. sort them and strcmp()
2. hash them ( function should be independent of characte sequence) and if they map to same value they are anagrams.
3. assign primary numbers to each letter of the word. get the product. do the same with target. if product matches then they are anagrams.