Trie Implementation

About

A Trie (pronounced "try") is a tree-like data structure used for storing a dynamic set of strings, often for fast retrieval of words with common prefixes.

Operations in Trie

Insert (O(n))

  • Traverse the Trie following each character in the word.

  • If a character’s node does not exist, create a new node.

  • Mark the last node as an end of a word.

Search (O(n))

  • Traverse the Trie following each character in the word.

  • If we reach the last character and the node is marked as an end of a word, return true.

  • Otherwise, return false.

Starts With (Prefix Search) (O(n))

  • Similar to search, but instead of checking the end of word, just ensure the prefix exists.

Delete (O(n))

  • Perform a search for the word.

  • If found, unmark the last character’s end of word flag.

  • Recursively delete unused nodes (if they are not part of another word).

Trie Implementation in Java

Time Complexity Analysis

Operation
Time Complexity

Insert

O(n)

Search

O(n)

Starts With

O(n)

Delete

O(n)

Print All Words

O(n)

n = length of the word being inserted/searched

Last updated