Pseudo Code for Trie Data Structure

Pseudo Code for Trie Data Structure
//  

Class TrieNode:
  isEndOfWord: Boolean  // Indicates if this node marks the end of a valid word
  children: Dictionary<Character, TrieNode>  // Maps characters to child nodes

  Constructor():
    isEndOfWord = False
    children = new empty Dictionary

Class Trie:
  root: TrieNode

  Constructor():
    root = new TrieNode()

  // Insert a word into the Trie
  Function insert(word: String):
    currentNode = root
    for each character in word:
      if character is not in currentNode.children:
        currentNode.children[character] = new TrieNode()
      currentNode = currentNode.children[character]
    currentNode.isEndOfWord = True

  // Search for a word in the Trie
  Function search(word: String): Boolean
    currentNode = root
    for each character in word:
      if character is not in currentNode.children:
        return False  // Word not found

      currentNode = currentNode.children[character]

    return currentNode.isEndOfWord  // True if the path ends at a word

  // Check if there is any word in the Trie that starts with the given prefix
  Function startsWith(prefix: String): Boolean
    currentNode = root
    for each character in prefix:
      if character is not in currentNode.children:
        return False  // Prefix not found

      currentNode = currentNode.children[character]

    return True  // A path exists for the prefix

  // Delete a word from the Trie (optional, more complex)
  Function delete(word: String): Boolean
    Function deleteRecursive(node: TrieNode, word: String, index: Integer): Boolean
      if index == length(word):
        if not node.isEndOfWord:
          return False  // Word not in Trie
        node.isEndOfWord = False
        // If this node has no other children and is not the end of another word,
        // it can be deleted on the way back up.
        return isEmpty(node.children)

      character = word[index]
      if character is not in node.children:
        return False  // Word not in Trie

      shouldDeleteChild = deleteRecursive(node.children[character], word, index + 1)

      if shouldDeleteChild and isEmpty(node.children[character]) and not node.isEndOfWord:
        remove node.children[character]

      return isEmpty(node.children) and not node.isEndOfWord

    return deleteRecursive(root, word, 0)

  // Helper function to check if a node's children dictionary is empty
  Function isEmpty(dictionary: Dictionary): Boolean
    return size(dictionary) == 0

// Example Usage:
trie = new Trie()
trie.insert("apple")
trie.insert("apricot")
trie.insert("banana")

print(trie.search("apple"))      // Output: True
print(trie.search("app"))        // Output: False
print(trie.startsWith("app"))    // Output: True
print(trie.startsWith("ban"))    // Output: True
print(trie.search("banana"))     // Output: True

trie.delete("apple")
print(trie.search("apple"))      // Output: False
print(trie.startsWith("app"))    // Output: True (because "apricot" still exists)

trie.delete("apricot")
print(trie.startsWith("app"))    // Output: False

print(trie.search("banana"))     // Output: True
trie.delete("banana")
print(trie.search("banana"))     // Output: False
print(trie.startsWith("ban"))    // Output: False
    

Explanation of the :

The pseudo code outlines the structure and operations of a Trie data structure.

  • TrieNode Class: Represents a single node in the Trie.
    • isEndOfWord: A boolean indicating if the path to this node forms a complete word.
    • children: A dictionary mapping characters to child TrieNode objects, representing the branches.
  • Trie Class: Represents the Trie data structure itself.
    • root: The starting, empty node of the Trie.
    • insert(word): Inserts a given word into the Trie by traversing or creating nodes for each character. The isEndOfWord flag of the last node is set to True.
    • search(word): Searches for a given word in the Trie. It returns True if the word exists and the path ends at a node where isEndOfWord is True, otherwise False.
    • startsWith(prefix): Checks if any word in the Trie starts with the given prefix. It returns True if a path exists for the entire prefix, otherwise False.
    • delete(word) (Optional, Recursive): Deletes a given word from the Trie. This implementation is recursive and can also remove unnecessary nodes if they no longer form part of any word.
    • isEmpty(dictionary) (Helper): A utility function to check if a dictionary of children is empty.

The example usage demonstrates how to create a Trie, insert words, search for words and prefixes, and delete words.

Agentic AI AI AI Agent Algorithm Algorithms API Automation AWS Azure Chatbot cloud cpu database Databricks Data structure Design embeddings gcp Generative AI indexing interview java Kafka Life LLM LLMs Micro Services monitoring Monolith N8n Networking Optimization Platform Platforms productivity python Q&A RAG redis Spark sql time series vector Vertex AI Workflow

Leave a Reply

Your email address will not be published. Required fields are marked *