Amazon interview question

Design Dictionary using TRIE (write insert and search function for TRIE)

Interview Answer

Anonymous

7 Sept 2011

I guess this would be difficult if you don't know what a trie is. Every node has a letter, 26 children (a-z), and a value for the key that corresponds to the current node. The most straightforward way to implement this is for each node to have an array of size 26. So, both search and insert would just walk down a string letter by letter and then traverse the trie based on the current letter. Specifically, for letter c in the string, visit child[lower(c) - 'a']. If the visited node's letter isn't equal to c (i.e., it's null), the key doesn't exist and we need to either add it or return "not found" depending on which function this is. Coding-wise a common mistake would probably be not using reference parameters for the insert.