interviews icon indicating copy to clipboard operation
interviews copied to clipboard

interviews/company/facebook/GroupAnagrams.java

Open knasim opened this issue 6 years ago • 2 comments

The given solution for this can be improved by not having to sort at all.
There are 2 calls to Arrays.sort().... This can become expensive if the program input array is large over 10K. A faster solution would just be to compute the hash of each value using a prime number assigned to each letter from a-z ( can be quckly generate in code). Then for each value in the array compute hash and store it inside a map. Then to get all the grouped anagrams you lookup the map or insert whatever the case maybe. I can provide code...too

knasim avatar Aug 02 '18 21:08 knasim

I don't think there is any reason for using the first sort. It would anyhow group together using just one sort method in inner loop. Coming to your approach, how sure are you that there would be no hash collisions?

GauravMohla avatar Aug 03 '18 20:08 GauravMohla

yes no need to sort. collisions ? a solid hash function. but since this is an interview question - the interviewer (depending on their degree of analness) may not dig you for that.

knasim avatar Aug 13 '18 20:08 knasim