{"id":815,"date":"2024-10-14T14:28:54","date_gmt":"2024-10-14T08:58:54","guid":{"rendered":"https:\/\/codexplained.in\/?p=815"},"modified":"2025-11-24T15:42:10","modified_gmt":"2025-11-24T10:12:10","slug":"implementation-of-tire-data-structure","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=815","title":{"rendered":"Implementation of Tire Data Structure"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Key Features of a Trie<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Node Structure<\/strong>: Each node in the Trie contains an array of pointers (one for each character) and a boolean flag to indicate if the node marks the end of a valid word.<\/li>\n\n\n\n<li><strong>Insertion<\/strong>: To insert a word, you traverse down the Trie, creating new nodes as needed for each character.<\/li>\n\n\n\n<li><strong>Search<\/strong>: To search for a word, you follow the path down the Trie according to the characters in the word.<\/li>\n\n\n\n<li><strong>Prefix Search<\/strong>: You can also search for all words that start with a given prefix.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">C Program to Implement a Trie Data Structure<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;stdbool.h&gt;\n#include &lt;string.h&gt;\n\n#define ALPHABET_SIZE 26 \/\/ Assuming only lowercase letters a-z\n#define MAX_WORD_LENGTH 100 \/\/ Maximum length for a word\n\n\/\/ Trie node structure\nstruct TrieNode {\n    struct TrieNode* children&#x5B;ALPHABET_SIZE];\n    bool isEndOfWord; \/\/ True if the node represents the end of a word\n};\n\n\/\/ Function to create a new Trie node\nstruct TrieNode* createNode() {\n    struct TrieNode* newNode = (struct TrieNode*)malloc(sizeof(struct TrieNode));\n    newNode-&gt;isEndOfWord = false;\n    for (int i = 0; i &lt; ALPHABET_SIZE; i++) {\n        newNode-&gt;children&#x5B;i] = NULL; \/\/ Initialize all children to NULL\n    }\n    return newNode;\n}\n\n\/\/ Function to insert a word into the Trie\nvoid insert(struct TrieNode* root, const char* word) {\n    struct TrieNode* currentNode = root;\n\n    while (*word) {\n        int index = *word - &#039;a&#039;; \/\/ Calculate index for the current character\n        if (!currentNode-&gt;children&#x5B;index]) {\n            currentNode-&gt;children&#x5B;index] = createNode(); \/\/ Create new node if it doesn&#039;t exist\n        }\n        currentNode = currentNode-&gt;children&#x5B;index]; \/\/ Move to the next node\n        word++; \/\/ Move to the next character\n    }\n    currentNode-&gt;isEndOfWord = true; \/\/ Mark the end of the word\n}\n\n\/\/ Function to search for a word in the Trie\nbool search(struct TrieNode* root, const char* word) {\n    struct TrieNode* currentNode = root;\n\n    while (*word) {\n        int index = *word - &#039;a&#039;;\n        if (!currentNode-&gt;children&#x5B;index]) {\n            return false; \/\/ If the character doesn&#039;t exist, word not found\n        }\n        currentNode = currentNode-&gt;children&#x5B;index];\n        word++;\n    }\n    return currentNode-&gt;isEndOfWord; \/\/ Return true if it&#039;s the end of a valid word\n}\n\n\/\/ Function to check if there is any word in the Trie that starts with the given prefix\nbool startsWith(struct TrieNode* root, const char* prefix) {\n    struct TrieNode* currentNode = root;\n\n    while (*prefix) {\n        int index = *prefix - &#039;a&#039;;\n        if (!currentNode-&gt;children&#x5B;index]) {\n            return false; \/\/ If the prefix doesn&#039;t exist, return false\n        }\n        currentNode = currentNode-&gt;children&#x5B;index];\n        prefix++;\n    }\n    return true; \/\/ Prefix found\n}\n\n\/\/ Main function to demonstrate the Trie operations\nint main() {\n    struct TrieNode* root = createNode(); \/\/ Create the root node\n\n    int choice;\n    char word&#x5B;MAX_WORD_LENGTH];\n\n    \/\/ Interactive menu for Trie operations\n    while (1) {\n        printf(&quot;1. Insert a word\\n&quot;);\n        printf(&quot;2. Search for a word\\n&quot;);\n        printf(&quot;3. Check for a prefix\\n&quot;);\n        printf(&quot;4. Exit\\n&quot;);\n        printf(&quot;Enter your choice: &quot;);\n        scanf(&quot;%d&quot;, &amp;choice);\n        getchar(); \/\/ Consume newline character\n\n        switch (choice) {\n            case 1:\n                printf(&quot;Enter a word to insert: &quot;);\n                fgets(word, sizeof(word), stdin);\n                word&#x5B;strcspn(word, &quot;\\n&quot;)] = &#039;\\0&#039;; \/\/ Remove newline character\n                insert(root, word);\n                printf(&quot;Inserted: %s\\n&quot;, word);\n                break;\n            case 2:\n                printf(&quot;Enter a word to search: &quot;);\n                fgets(word, sizeof(word), stdin);\n                word&#x5B;strcspn(word, &quot;\\n&quot;)] = &#039;\\0&#039;; \/\/ Remove newline character\n                printf(&quot;Searching for &#039;%s&#039;: %s\\n&quot;, word, search(root, word) ? &quot;Found&quot; : &quot;Not Found&quot;);\n                break;\n            case 3:\n                printf(&quot;Enter a prefix to check: &quot;);\n                fgets(word, sizeof(word), stdin);\n                word&#x5B;strcspn(word, &quot;\\n&quot;)] = &#039;\\0&#039;; \/\/ Remove newline character\n                printf(&quot;Prefix &#039;%s&#039;: %s\\n&quot;, word, startsWith(root, word) ? &quot;Exists&quot; : &quot;Does not exist&quot;);\n                break;\n            case 4:\n                printf(&quot;Exiting...\\n&quot;);\n                free(root); \/\/ Free the allocated memory\n                return 0;\n            default:\n                printf(&quot;Invalid choice. Please try again.\\n&quot;);\n        }\n    }\n    return 0;\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Explanation of the Updated Code<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>User Interaction<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The program now presents a simple menu for the user to choose from inserting a word, searching for a word, checking a prefix, or exiting.<\/li>\n\n\n\n<li>The user can input words and prefixes directly, making it more interactive.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Input Handling<\/strong>:\n<ul class=\"wp-block-list\">\n<li><code>fgets<\/code> is used to read strings, allowing for spaces in input. The newline character is removed using <code>strcspn<\/code> to ensure the strings are formatted correctly.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Dynamic Operations<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The Trie operations remain the same (insert, search, prefix checking), but now they respond to user inputs in real-time.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">How to Run the Program<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Compile the code using a C compiler (e.g., <code>gcc<\/code>):Copy code<code>gcc trie.c -o trie<\/code><\/li>\n\n\n\n<li>Run the compiled program:bashCopy code<code>.\/trie<\/code><\/li>\n\n\n\n<li>Follow the prompts to insert words, search for them, and check prefixes.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Sample Input and Output<\/h3>\n\n\n\n<p>Here\u2019s how a sample interaction with the program might look:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">mathematicaCopy code<code>1. Insert a word\n2. Search for a word\n3. Check for a prefix\n4. Exit\nEnter your choice: 1\nEnter a word to insert: hello\nInserted: hello\n1. Insert a word\n2. Search for a word\n3. Check for a prefix\n4. Exit\nEnter your choice: 1\nEnter a word to insert: hi\nInserted: hi\n1. Insert a word\n2. Search for a word\n3. Check for a prefix\n4. Exit\nEnter your choice: 2\nEnter a word to search: hello\nSearching for 'hello': Found\n1. Insert a word\n2. Search for a word\n3. Check for a prefix\n4. Exit\nEnter your choice: 3\nEnter a prefix to check: he\nPrefix 'he': Exists\n1. Insert a word\n2. Search for a word\n3. Check for a prefix\n4. Exit\nEnter your choice: 4\nExiting...\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>This updated implementation of the Trie allows for dynamic interaction and showcases the functionalities effectively. You can test various words and prefixes, making it a practical tool for understanding how Tries work.<\/p>\n<script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script><script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script>","protected":false},"excerpt":{"rendered":"<p>Key Features of a Trie C Program to Implement a Trie Data Structure Explanation of the Updated Code How to Run the Program Sample Input and Output Here\u2019s how a sample interaction with the program might look: mathematicaCopy code1. Insert a word 2. Search for a word 3. Check for a prefix 4. Exit Enter [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":820,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[75],"tags":[],"class_list":["post-815","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/815","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=815"}],"version-history":[{"count":4,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/815\/revisions"}],"predecessor-version":[{"id":1421,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/815\/revisions\/1421"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/820"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=815"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=815"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=815"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}