AlgoMaster Logo

Implement Trie (Prefix Tree)

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Basic Trie Implementation

Intuition:

The basic idea of a Trie is to store strings in a tree-like structure where each node represents a single character. Each path down the tree represents a string. We add two special features to our nodes:

  1. A way to know if they represent the end of a valid string.
  2. Pointers to traverse to the next node based on the next character.

We'll implement the basic Trie operations:

  • Insert: Traverse character by character, creating nodes if they don't exist.
  • Search: Traverse character by character to see if the whole word exists.
  • StartsWith: Similar to search, but only checks if the prefix exists.

Code:

2. Optimized Trie Implementation with HashMap

Intuition:

Instead of using a fixed size array for the children nodes, we can use a HashMap to dynamically store only the necessary characters. This saves space, especially in cases where the alphabet size is large or the set of possible characters is sparse.

Code: