Tutorialspoint
Problem
Solution
Submissions

Trie (Prefix Tree) Data Structure

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 15

Write a program to implement a Trie (Prefix Tree) data structure for efficient word storage and retrieval.

Example 1
  • Input:
    ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
    [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
  • Output:
    [null, null, true, false, true, null, true]
  • Explanation:
    • Insert "apple", search returns true.
    • Search "app" returns false.
    • startsWith("app") is true.
    • Insert "app", now search returns true.
Example 2
  • Input:
    ["Trie", "insert", "insert", "search", "startsWith", "search"]
    [[], ["hello"], ["world"], ["world"], ["worl"], ["wor"]]
  • Output:
    [null, null, null, true, true, false]
  • Explanation:
    • Insert "hello" and "world".
    • search("world") returns true.
    • startsWith("worl") true, search("wor") false.
Constraints
  • 1 ≤ word.length, prefix.length ≤ 2000
  • Only lowercase English letters allowed
  • At most 3 * 10^4 calls to insert/search/startsWith
  • Time Complexity: O(m)
  • Space Complexity: O(n * m)
Trie TreeHCL TechnologiesApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a tree-like data structure where each node represents a single character
  • Each node should contain links to child nodes, one for each possible character
  • Mark nodes that represent the end of a word
  • For startsWith(), you only need to check if the prefix path exists
  • For search(), check if the path exists AND if the last node is marked as the end of a word

Steps to solve by this approach:

 Step 1: Create a TrieNode class that will serve as the building block for our Trie. Each node contains a hashmap of children and a boolean flag indicating if it's the end of a word.

 Step 2: Implement the Trie class with a root TrieNode.
 Step 3: For insertion, traverse the Trie character by character, creating new nodes as needed, and mark the final node as the end of a word.
 Step 4: For searching, traverse the Trie following the path of the word. Return true only if the final node exists and is marked as the end of a word.
 Step 5: For startsWith, traverse the Trie following the path of the prefix. Return true if the entire prefix path exists, regardless of whether it's marked as the end of a word.

Submitted Code :