faster solution using trie, but still not good enough