Vertical traverse
After trying to figure out how to approach the problem for about 20 minutes, my interviewer was nice enough to give me a similar but slightly easier problem: Given a binary tree, print out the sum of each column. So given the above tree, the output should be 1 2 12 6 7
How did I approach it?
● I mentioned the obvious brute force solution: iterating over the words and comparing each word to the search term passed in. The runtime would be O(array.length * longest_word.length)
● Since you can preprocess the array, I tried to sort it in alphabetical order and then perform binary search on the search term, which should speed up the function slightly.
● I also tried a hash table implementation which store the first character of the string as the key and the value would be a linked list of all strings that start with that character. However, in the worst case where all words in the array start with the same letter, we would essentially be doing the brute force solution + the work of converting the array into a hash table.
● The correct solution involved building a trie containing all the words in the array and then traversing down the trie character by character to see if the search term passed in was contained within that trie. If we reached a leaf node in the trie and the word wasn’t complete, then we simply return false. To account for the wild card, when we get to that character in the trie represented by the wild card, we would simply move onto the next character.