Movatterモバイル変換


[0]ホーム

URL:


Data Structures & Algorithms Tutorial

Suffix Tries



A suffix trie is a type of trie mainly used for representing all the suffixes of a string. It is a tree where each node represents the suffix of a string. The root node is the entire string, and each child node is a suffix of the string that's one character shorter than the parent node's suffix.

For example, consider the string "banana". The suffix trie for this string would look like this:

             root           /  | \          b   a  n         /    |   \         a    n    a        /     |     \        n     a      n       /      |       \      a       n        a     /        |         \    n         a          $   /          |  a           $ /$

Each path from the root to a leaf node represents a suffix of the string. The leaf nodes represent the end of a suffix, and the dollar sign($) is used to indicate the end of the string.

The children store entire word instead of characters.

Features of Suffix Tries

Following are the Features of Suffix Tries −

    It is trie, so it stores suffixes of string in trie data structure. for string of length n, there are n suffixes.

    We can say compact representation of all suffixes of a string. Means, to save space, it becomesSuffix Tree by collapsing the nodes with only one child.

    Suffix tries are effective for sub-string searches, pattern matching, and other string-related operations.

Operations on Suffix Tries

Some of the common operations on suffix tries include:

  • Insertion: Insert a new suffix into the trie.
  • Deletion: Remove a suffix from the trie.
  • Search: Find a specific suffix in the trie.

Insertion Operation on Suffix Tries

We can insert a new suffix into the trie by following these steps:

1. Start at the root node.2. For each character in the suffix:    a. If the character is not in the current node's children, create a new node for the same.    b. Then move to the child node corresponding to the character and repeat the process.3. Repeat the process for all character in the suffix.4. Mark the last node as a leaf node to indicate the end of the suffix.

Code for Insertion Operation

For example, to insert the suffix "ana" into the trie, we would follow these steps:

// C Program to insert a suffix into a trie#include <stdio.h>#include <stdlib.h>#define ALPHABET_SIZE 26// Structure for trie nodestruct TrieNode {   struct TrieNode* children[ALPHABET_SIZE];   int isEndOfWord;};// Function to create a new trie nodestruct TrieNode* createNode() {   struct TrieNode* node = (struct TrieNode*)malloc(sizeof(struct TrieNode));   node->isEndOfWord = 0;   for (int i = 0; i < ALPHABET_SIZE; i++) {      node->children[i] = NULL;   }   return node;}// Function to insert a suffix into the trievoid insert(struct TrieNode* root, const char* suffix) {   struct TrieNode* current = root;   for (int i = 0; suffix[i] != '\0'; i++) {      int index = suffix[i] - 'a';      if (current->children[index] == NULL) {         current->children[index] = createNode();      }      current = current->children[index];   }   current->isEndOfWord = 1;}// Display the trievoid display(struct TrieNode* root, char str[], int level) {   if (root->isEndOfWord) {      str[level] = '\0';      printf("%s\n", str);   }   for (int i = 0; i < ALPHABET_SIZE; i++) {      if (root->children[i] != NULL) {         str[level] = i + 'a';         display(root->children[i], str, level + 1);      }   }}int main() {   struct TrieNode* root = createNode();   insert(root, "banana");   insert(root, "ana");   insert(root, "na");   insert(root, "a");   insert(root, "$");   char str[20];  // Allocating memory for string buffer   display(root, str, 0);   return 0;}

Output

Following is the output of the above code:

aanabananana
// C++ Program to insert a suffix into a trie#include <iostream>#include <vector>using namespace std;#define ALPHABET_SIZE 26// Structure for trie nodestruct TrieNode {   TrieNode* children[ALPHABET_SIZE];   bool isEndOfWord;};// Function to create a new trie nodeTrieNode* createNode() {   TrieNode* node = new TrieNode();   node->isEndOfWord = false;   for (int i = 0; i < ALPHABET_SIZE; i++) {      node->children[i] = NULL;   }   return node;}// Function to insert a suffix into the trievoid insert(TrieNode* root, const string& suffix) {   TrieNode* current = root;   for (char c : suffix) {      int index = c - 'a';      if (current->children[index] == NULL) {         current->children[index] = createNode();      }      current = current->children[index];   }   current->isEndOfWord = true;}// Display the trievoid display(TrieNode* root, char str[], int level) {   if (root->isEndOfWord) {      str[level] = '\0';      cout << str << endl;   }   for (int i = 0; i < ALPHABET_SIZE; i++) {      if (root->children[i] != NULL) {         str[level] = i + 'a';         display(root->children[i], str, level + 1);      }   }}int main() {   TrieNode* root = createNode();   insert(root, "banana");   insert(root, "ana");   insert(root, "na");   insert(root, "a");   insert(root, "$");   char str[20];  // Allocating memory for string buffer   display(root, str, 0);   return 0;}

Output

Following is the output of the above code:

aanabananana
// Java Program to insert a suffix into a trieclass TrieNode {   TrieNode[] children;   boolean isEndOfWord;   TrieNode() {      children = new TrieNode[26]; // Only 'a' to 'z'      isEndOfWord = false;   }}public class Main {   static final int ALPHABET_SIZE = 26;   // Function to insert a suffix into the trie   static void insert(TrieNode root, String suffix) {      TrieNode current = root;      for (int i = 0; i < suffix.length(); i++) {         char ch = suffix.charAt(i);         // Ignore non-alphabet characters         if (ch < 'a' || ch > 'z') continue;         int index = ch - 'a';         if (current.children[index] == null) {            current.children[index] = new TrieNode();         }         current = current.children[index];      }      current.isEndOfWord = true;   }   // Display the trie   static void display(TrieNode root, char[] str, int level) {      if (root.isEndOfWord) {         System.out.println(new String(str, 0, level)); // Correct substring printing      }      for (int i = 0; i < ALPHABET_SIZE; i++) {         if (root.children[i] != null) {            str[level] = (char) (i + 'a');            display(root.children[i], str, level + 1);         }      }   }   public static void main(String[] args) {      TrieNode root = new TrieNode();      insert(root, "banana");      insert(root, "ana");      insert(root, "na");      insert(root, "a");      insert(root, "$");  // '$' will be ignored safely      char[] str = new char[20];  // Allocating memory for string buffer      display(root, str, 0);   }}

Output

Following is the output of the above code:

aanabananana
# Python Program to insert a suffix into a trie# Python Program to insert a suffix into a trieclass TrieNode:    def __init__(self):        self.children = [None] * 26  # Only for 'a' to 'z'        self.isEndOfWord = False# Function to insert a suffix into the triedef insert(root, suffix):    current = root    for c in suffix:        # Ignore non-alphabet characters        if not ('a' <= c <= 'z'):            continue  # Skip invalid characters        index = ord(c) - ord('a')        if current.children[index] is None:            current.children[index] = TrieNode()        current = current.children[index]    current.isEndOfWord = True# Display the triedef display(root, str, level):    if root.isEndOfWord:        print(''.join(str[:level]))  # Print valid words    for i in range(26):        if root.children[i] is not None:            str[level] = chr(i + ord('a'))            display(root.children[i], str, level + 1)if __name__ == '__main__':    root = TrieNode()    insert(root, "banana")    insert(root, "ana")    insert(root, "na")    insert(root, "a")    insert(root, "$")  # '$' will be ignored safely    str = [''] * 20  # Allocating memory for string buffer    display(root, str, 0)

Output

Following is the output of the above code:

aanabananana

Deletion and Search Operations on Suffix Tries

Deletion and search operations on suffix tries are similar to insertion. We can delete a suffix by removing the corresponding leaf node from the trie. To search for a specific suffix, we can traverse the trie from the root node to the leaf node corresponding to the suffix.

Following are the steps to delete a suffix from the trie:

1. Start at the root node.2. For each character in the suffix:    a. Move to the child node corresponding to the character.3. Mark the last node as a non-leaf node to delete the suffix.

Following are the steps to search for a specific suffix in the trie:

1. Start at the root node.2. For each character in the suffix:    a. Move to the child node corresponding to the character.3. Check if the last node is a leaf node to find the suffix.

Code for Deletion and Search Operations

Here is the code for deletion and search operations on suffix tries:

// C Program to delete and search a suffix in a trie#include <stdio.h>#include <stdlib.h>#define ALPHABET_SIZE 26// Structure for trie nodestruct TrieNode {   struct TrieNode* children[ALPHABET_SIZE];   int isEndOfWord;};// Function to create a new trie nodestruct TrieNode* createNode() {   struct TrieNode* node = (struct TrieNode*)malloc(sizeof(struct TrieNode));   node->isEndOfWord = 0;   for (int i = 0; i < ALPHABET_SIZE; i++) {      node->children[i] = NULL;   }   return node;}// Function to insert a suffix into the trievoid insert(struct TrieNode* root, const char* suffix) {   struct TrieNode* current = root;   for (int i = 0; suffix[i] != '\0'; i++) {      int index = suffix[i] - 'a';      if (current->children[index] == NULL) {         current->children[index] = createNode();      }      current = current->children[index];   }   current->isEndOfWord = 1;}// Function to delete a suffix from the trievoid delete(struct TrieNode* root, const char* suffix) {   struct TrieNode* current = root;   for (int i = 0; suffix[i] != '\0'; i++) {      int index = suffix[i] - 'a';      if (current->children[index] == NULL) {         return;  // Suffix not found      }      current = current->children[index];   }   current->isEndOfWord = 0;}// Function to search for a suffix in the trieint search(struct TrieNode* root, const char* suffix) {   struct TrieNode* current = root;   for (int i = 0; suffix[i] != '\0'; i++) {      int index = suffix[i] - 'a';      if (current->children[index] == NULL) {         return 0;  // Suffix not found      }      current = current->children[index];   }   return current->isEndOfWord;}int main() {   struct TrieNode* root = createNode();   insert(root, "banana");   insert(root, "ana");   insert(root, "na");   insert(root, "a");   insert(root, "$");   printf("Search for 'ana': %s\n", search(root, "ana") ? "Found" : "Not found");   delete(root, "ana");   printf("After deletion:\n");   printf("Search for 'ana': %s\n", search(root, "ana") ? "Found" : "Not found");   printf("Search for 'na': %s\n", search(root, "na") ? "Found" : "Not found");   return 0;}

Output

Following is the output of the above code:

Search for 'ana': FoundAfter deletion:Search for 'ana': Not foundSearch for 'na': Found
// C++ Program to delete and search a suffix in a trie#include <iostream>#include <vector>using namespace std;#define ALPHABET_SIZE 26// Structure for trie nodestruct TrieNode {   TrieNode* children[ALPHABET_SIZE];   bool isEndOfWord;};// Function to create a new trie nodeTrieNode* createNode() {   TrieNode* node = new TrieNode();   node->isEndOfWord = false;   for (int i = 0; i < ALPHABET_SIZE; i++) {      node->children[i] = NULL;   }   return node;}// Function to insert a suffix into the trievoid insert(TrieNode* root, const string& suffix) {   TrieNode* current = root;   for (char c : suffix) {      int index = c - 'a';      if (current->children[index] == NULL) {         current->children[index] = createNode();      }      current = current->children[index];   }   current->isEndOfWord = true;}// Function to delete a suffix from the trievoid deleteN(TrieNode* root, const string& suffix) {   TrieNode* current = root;   for (char c : suffix) {      int index = c - 'a';      if (current->children[index] == NULL) {         return;  // Suffix not found      }      current = current->children[index];   }   current->isEndOfWord = false;}// Function to search for a suffix in the triebool search(TrieNode* root, const string& suffix) {   TrieNode* current = root;   for (char c : suffix) {      int index = c - 'a';      if (current->children[index] == NULL) {         return false;  // Suffix not found      }      current = current->children[index];   }   return current->isEndOfWord;}int main() {   TrieNode* root = createNode();   insert(root, "banana");   insert(root, "ana");   insert(root, "na");   insert(root, "a");   insert(root, "$");   cout << "Search for 'ana': " << (search(root, "ana") ? "Found" : "Not found") << endl;   deleteN(root, "ana");   cout << "After deletion:\n";   cout << "Search for 'ana': " << (search(root, "ana") ? "Found" : "Not found") << endl;   cout << "Search for 'na': " << (search(root, "na") ? "Found" : "Not found") << endl;   return 0;}

Output

Following is the output of the above code:

Search for 'ana': FoundAfter deletion:Search for 'ana': Not foundSearch for 'na': Found
// Java Program to delete and search a suffix in a trieclass TrieNode {   TrieNode[] children;   boolean isEndOfWord;   TrieNode() {      children = new TrieNode[26]; // Only 'a' to 'z'      isEndOfWord = false;   }}public class Main {   static final int ALPHABET_SIZE = 26;   // Function to insert a suffix into the trie   static void insert(TrieNode root, String suffix) {      TrieNode current = root;      for (int i = 0; i < suffix.length(); i++) {         char ch = suffix.charAt(i);         // Ignore non-alphabet characters         if (ch < 'a' || ch > 'z') continue;         int index = ch - 'a';         if (current.children[index] == null) {            current.children[index] = new TrieNode();         }         current = current.children[index];      }      current.isEndOfWord = true;   }   // Function to delete a suffix from the trie   static void delete(TrieNode root, String suffix) {      TrieNode current = root;      for (int i = 0; i < suffix.length(); i++) {         char ch = suffix.charAt(i);         // Ignore non-alphabet characters         if (ch < 'a' || ch > 'z') return;         int index = ch - 'a';         if (current.children[index] == null) {            return;  // Suffix not found         }         current = current.children[index];      }      current.isEndOfWord = false;   }   // Function to search for a suffix in the trie   static boolean search(TrieNode root, String suffix) {      TrieNode current = root;      for (int i = 0; i < suffix.length(); i++) {         char ch = suffix.charAt(i);         // Ignore non-alphabet characters         if (ch < 'a' || ch > 'z') return false;         int index = ch - 'a';         if (current.children[index] == null) {            return false;  // Suffix not found         }         current = current.children[index];      }      return current.isEndOfWord;   }   public static void main(String[] args) {      TrieNode root = new TrieNode();      insert(root, "banana");      insert(root, "ana");      insert(root, "na");      insert(root, "a");      insert(root, "$");      System.out.println("Search for 'ana': " + (search(root, "ana") ? "Found" : "Not found"));      delete(root, "ana");      System.out.println("After deletion:");      System.out.println("Search for 'ana': " + (search(root, "ana") ? "Found" : "Not found"));      System.out.println("Search for 'na': " + (search(root, "na") ? "Found" : "Not found"));   }}

Output

Following is the output of the above code:

Search for 'ana': FoundAfter deletion:Search for 'ana': Not foundSearch for 'na': Found
# Python Program to delete and search a suffix in a trieclass TrieNode:    def __init__(self):        self.children = [None] * 26  # Only for 'a' to 'z'        self.isEndOfWord = False# Function to insert a suffix into the triedef insert(root, suffix):    current = root    for c in suffix:        # Ignore non-alphabet characters        if not ('a' <= c <= 'z'):            continue  # Skip invalid characters        index = ord(c) - ord('a')        if current.children[index] is None:            current.children[index] = TrieNode()        current = current.children[index]    current.isEndOfWord = True# Function to delete a suffix from the triedef delete(root, suffix):    current = root    for c in suffix:        # Ignore non-alphabet characters        if not ('a' <= c <= 'z'):            return  # Skip invalid characters        index = ord(c) - ord('a')        if current.children[index] is None:            return  # Suffix not found        current = current.children[index]    current.isEndOfWord = False# Function to search for a suffix in the triedef search(root, suffix):    current = root    for c in suffix:        # Ignore non-alphabet characters        if not ('a' <= c <= 'z'):            return False  # Skip invalid characters        index = ord(c) - ord('a')        if current.children[index] is None:            return False  # Suffix not found        current = current.children[index]    return current.isEndOfWordif __name__ == '__main__':   root = TrieNode()   insert(root, "banana")   insert(root, "ana")   insert(root, "na")   insert(root, "a")   insert(root, "$")   print("Search for 'ana':", "Found" if search(root, "ana") else "Not found")   delete(root, "ana")   print("After deletion:")   print("Search for 'ana':", "Found" if search(root, "ana") else "Not found")   print("Search for 'na':", "Found" if search(root, "na") else "Not found")

Output

Following is the output of the above code:

Search for 'ana': FoundAfter deletion:Search for 'ana': Not foundSearch for 'na': Found

Time Complexity of Suffix Tries

The time complexity of suffix tries depends on the operations performed:

  • Insertion: O(n) for inserting a suffix of length n into the trie.
  • Deletion: O(n)
  • Search: O(n)

Applications of Suffix Tries

Suffix tries are used in various applications, including:

  • Pattern matching and substring search algorithms
  • Text indexing and searching
  • Genomic sequence analysis
  • Spell checking and correction
  • Biological sequence analysis
  • Information retrieval
  • Compression algorithms

Conclusion

In this chapter, we discussed suffix tries, a type of trie used for representing all the suffixes of a string. We explored the structure of a suffix trie, its features, operations, and applications. Suffix tries are a powerful data structure for substring searches, pattern matching, and other string-related operations.

Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp