ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Implement Trie (Prefix Tree)

C

Goal -- WPM

Ready
Exercise Algorithm Area
1#include <stdio.h>
2#include <stdlib.h>
3#include <stdbool.h>
4#include <string.h>
5
6#define ALPHABET_SIZE 26
7
8// Trie node structure
9typedef struct TrieNode {
10struct TrieNode *children[ALPHABET_SIZE];
11bool isEndOfWord;
12} TrieNode;
13
14// Function to create a new Trie node
15TrieNode* createNode() {
16TrieNode* newNode = (TrieNode*) malloc(sizeof(TrieNode));
17if (!newNode) {
18perror("Failed to allocate memory for TrieNode");
19exit(EXIT_FAILURE);
20}
21
22newNode->isEndOfWord = false;
23for (int i = 0; i < ALPHABET_SIZE; i++) {
24newNode->children[i] = NULL;
25}
26return newNode;
27}
28
29// Function to insert a word into the Trie
30void insert(TrieNode* root, const char* word) {
31TrieNode* currentNode = root;
32int length = strlen(word);
33
34for (int i = 0; i < length; i++) {
35// Assuming only lowercase English letters
36int index = word[i] - 'a';
37if (index < 0 || index >= ALPHABET_SIZE) {
38fprintf(stderr, "Warning: Character '%c' out of expected range. Skipping.\n", word[i]);
39continue; // Skip invalid characters
40}
41
42if (!currentNode->children[index]) {
43currentNode->children[index] = createNode();
44}
45currentNode = currentNode->children[index];
46}
47
48// Mark the end of the word
49currentNode->isEndOfWord = true;
50}
51
52// Function to search for a word in the Trie
53bool search(TrieNode* root, const char* word) {
54TrieNode* currentNode = root;
55int length = strlen(word);
56
57for (int i = 0; i < length; i++) {
58int index = word[i] - 'a';
59if (index < 0 || index >= ALPHABET_SIZE) {
60return false; // Invalid character means word cannot exist
61}
62if (!currentNode->children[index]) {
63return false; // Path does not exist
64}
65currentNode = currentNode->children[index];
66}
67
68// Return true only if the path exists AND it marks the end of a word
69return (currentNode != NULL && currentNode->isEndOfWord);
70}
71
72// Helper function to free Trie memory (recursive)
73void freeTrie(TrieNode* node) {
74if (!node) {
75return;
76}
77for (int i = 0; i < ALPHABET_SIZE; i++) {
78freeTrie(node->children[i]);
79}
80free(node);
81}
82
83int main() {
84TrieNode* root = createNode();
85
86insert(root, "apple");
87insert(root, "app");
88insert(root, "apricot");
89insert(root, "banana");
90
91printf("Search 'apple': %s\n", search(root, "apple") ? "Found" : "Not Found");
92printf("Search 'app': %s\n", search(root, "app") ? "Found" : "Not Found");
93printf("Search 'apricot': %s\n", search(root, "apricot") ? "Found" : "Not Found");
94printf("Search 'banana': %s\n", search(root, "banana") ? "Found" : "Not Found");
95printf("Search 'appl': %s\n", search(root, "appl") ? "Found" : "Not Found"); // Prefix, not a full word
96printf("Search 'orange': %s\n", search(root, "orange") ? "Found" : "Not Found");
97printf("Search 'a': %s\n", search(root, "a") ? "Found" : "Not Found"); // Single character word
98printf("Search 'ap': %s\n", search(root, "ap") ? "Found" : "Not Found"); // Prefix, not a full word
99
100// Test with empty string
101printf("Search '': %s\n", search(root, "") ? "Found" : "Not Found"); // Should be false unless explicitly inserted
102insert(root, ""); // Inserting empty string
103printf("Search '' after insert: %s\n", search(root, "") ? "Found" : "Not Found");
104
105// Test with invalid characters (should be handled gracefully)
106insert(root, "apple!"); // '!' is not in alphabet_size
107printf("Search 'apple!': %s\n", search(root, "apple!") ? "Found" : "Not Found");
108
109freeTrie(root);
110return 0;
111}
Algorithm description viewbox

Implement Trie (Prefix Tree)

Algorithm description:

This C code implements a Trie (prefix tree) data structure. It allows for efficient insertion and searching of words. Each node in the Trie represents a character, and paths from the root to a node represent prefixes. A special flag indicates if a node marks the end of a complete word. Tries are commonly used for autocomplete features, spell checkers, and dictionary implementations.

Algorithm explanation:

The Trie is a tree-like data structure where each node represents a character. The `createNode` function initializes a new node with its children pointers set to NULL and `isEndOfWord` to false. The `insert` function traverses the Trie, creating new nodes as needed for characters in the word, and marks the final node as `isEndOfWord = true`. The `search` function follows the path for the given word; if the path exists and the final node is marked as `isEndOfWord`, the word is found. The `freeTrie` function recursively deallocates memory to prevent leaks. The time complexity for both insert and search is O(L), where L is the length of the word, as we traverse at most L nodes. The space complexity depends on the number of nodes, which is related to the total number of characters in all inserted words and the branching factor (ALPHABET_SIZE). Edge cases include empty strings, words that are prefixes of other words, and invalid characters.

Pseudocode:

struct TrieNode:
  children[ALPHABET_SIZE] of TrieNode pointers
  isEndOfWord: boolean

function createNode():
  allocate memory for a new TrieNode
  initialize all children to NULL
  set isEndOfWord to false
  return the new node

function insert(root, word):
  currentNode = root
  for each character c in word:
    index = c - 'a'
    if children[index] is NULL:
      children[index] = createNode()
    currentNode = children[index]
  currentNode.isEndOfWord = true

function search(root, word):
  currentNode = root
  for each character c in word:
    index = c - 'a'
    if children[index] is NULL:
      return false
    currentNode = children[index]
  return currentNode.isEndOfWord

function freeTrie(node):
  if node is NULL:
    return
  for each child in node.children:
    freeTrie(child)
  free node