Google Interview Question

Write a code to find out if two string words are anagrams

Interview Answers

Anonymous

Nov 12, 2011

boolean areAnagrams?( String s1, String s2) { int s1Length = s1.length(), s2Length = s2.length(); if(s1Length != s2Length ) return false; 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 < s1Length; i++) { frequencies[ (int)s1.charAt(i) ]++; }//now we have an int array corresponding to letter frequencies for(int i = 0; i < s2Length; i++) { frequencies[ (int)s2.charAt(i) ]--; }//now, if they are anagrams, all will be zero for(int = 0; i < s1Length; i++) { if( frequencies[ (int)s1.charAt(i) ] ) {//evaluates to true for anything but zero return false; } } return true; }

3

Anonymous

Nov 4, 2011

Sort the characters in the words. Compare them. Complexity : O(n log n) depending on the sort algorithm.

2

Anonymous

May 1, 2012

@rob, for ascii assumption we will require array size of 256

Anonymous

Oct 17, 2011

First way is to use HashMaps (quick but not memory use effective) Second is to use arrays (memory effective but slower).