Refactored with trie-like data structure