User:Carl298/sandbox

A Java version of Trie methods are provided as follows.

A node in the Trie can be represented as: Insertion of Trie nodes works as follows: Searching for a word is shown here: We can also utilize the Trie Tree to check whether a prefix exists:

Sample Use Cases
There are many use cases for Trie. We will introduce one example here to illustrate how Trie can help reduce program space complexity.

2D Board Word Search with a Dictionary
We are given a 2D board filled with letters. We need to write a program to return all the valid words that can be found in this board; the words need to exist in a given dictionary to be considered valid. Each word must be constructed by adjacent cells sequentially, where adjacent cell is defined as a cell that is a horizontal or vertical neighbor of the current cell. A simple example is given below: Here is the Java code with extensive comments that solves this problem. The basic approach is to: 1. Start from every letter in this 2D board; 2. Do depth-first-search from such letter and try to construct a string that is a valid word. The Trie Tree will help reduce run time because we can prune many depth-first-search paths if one letter does not even follow another in dictionary words. Trie Tree is also very space-efficient here, since we are only storing the 26 English letters in it. We will analyze time and space complexity later.

Time Complexity
O(N * (4 * 3 ^ (L - 1))), where N is the number of cells in the given board, and L is the length of the longest word.

Explanation
We need to loop through every cell of the board, as every cell can be a starting point of a valid word; therefore M exists in the formula. For each cell, initially, we have at most 4 different directions we can go (up, down, left, right). And if we assume the worst case, each direction would be valid; therefore, there will be 3 neighboring cells we can explore (4 - 1 because we do not want to count the cell we are coming from). As a result, we would go through at most 4 * 3 ^ (L - 1) cells in each call of "combineLetters."

Space Complexity
O(N), where N is the number of valid words in the given dictionary.

Explanation
The reason is that Trie Tree will take at most 2N space.