Hacker News new | ask | show | jobs
by mmorett 4666 days ago
Lol!! You're killing me. I need to work tomorrow and you're gonna have me up all night thinking how to optimize this thing. It's only 5 lines of code.

Hashtable, huh? I don't like them because they're synchronized, but let's use a HashMap instead. Regardless, I'm stumped.

Let me think out loud. You'd probably want me to stick two entries in there with the words being the values. I suspect the keys are irrelevant. But I need the values themselves sorted prior to being placed in the map. Lets assume I stick the char arrays in the map. I still can't see how the map helps. Unless, I abandon the HashMap and go with a TreeMap instead. That negates the need to explicitly sort and maybe that's the time savings, but....

My head hurts. :-)

I don't know. I'd have to code this out and experiment a bit. But I like the push. You're forcing me to dig deeper.

PS. I can't build a search engine.

EDIT: A quick search of the net yields at least one answer (don't know if this works):

"We can solve this problem in O(n) time by using hashtable. That is, create a hashtable which record the times that the characters a-Z appear in S1 and create another hashtable for S2. If the two hashtables have the same content, then the strings are identical. This solution requires O(n) time to create two hashtables and compare them, and O(52) = O(1) space to store the hashtable."

I'm so disgusted. I was way off. Not even close. I wasn't even thinking in this direction. Does anyone have the number to that truck driving school?

1 comments

I'm pretty sure the sort solution would be an order of magnitude faster on any reasonably sized string. Big O's are Big O's : they are irrelevant when n is small, and for anagrams we're talking something like n < 45.