LEARNING JOURNAL

I created this learning journal to practice writting and to help me learn by writting everything down. Source code here

2/24/2024

Implement Trie (Prefix Tree)

THE PROBLEM

This is my solution for the Trie problem. I used the class TrieNode to represent each node in the Trie. Basically, each node has a value and a hash table to store all nodes that it connects. When search function is called, we traverse along the Trie. If somewhere along the way, we can not find the next node that has the value of the next character, we stop and return false. Otherwise, when we comes to the last character, we check if it has the end mark after it. If it is, we return true.

The catch here is how to add two words that have the same prefix to the trie. I use the "end" marker to denote the end of a word.

Revised by ChatGPT

This solution implements a Trie, a tree-like data structure used for efficient retrieval of strings. The key components are:

  • TrieNode Class: Represents each node in the Trie. It has a value (the character it represents) and a map (nexts) to store its children nodes. Each node also has a method isEnd to check is it's the end of a word.
  • Trie Class: Contains the root node (head) and methods for inserting, searching, and checking prefixes: insert(word): Adds a words to the Trie. Iterates through each character of the word, creating new nodes as needed. search(word): Checks if a word exists in the Trie. Traverses the Trie according to the word's characters and returns true if the end of the word is marked. startsWith(prefix): Checks if any word in the Trie starts with the given prefix. Similar to search, but doesn't require the end of the word to be marked.

The solution utilizes an "end" marker (implemented as a null value in nexts with the key "END") to denote the end of a word. This approach allows for efficient differentiation between words with common prefixes.