String Algorithm

Total Page:16

File Type:pdf, Size:1020Kb

String Algorithm Trie: A data-structure for a set of words All words over the alphabet Σ={a,b,..z}. In the slides, let say that the alphabet is only {a,b,c,d} S – set of words = {a,aba, a, aca, addd} Need to support the operations Tries and suffixes trees • insert(w) – add a new word w into S. • delete(w) – delete the word w from S. • find(w) is w in S ? Alon Efrat • Future operation: Computer Science Department • Given text (many words) where is w in the text. University of Arizona • The time for each operation should be O(k), where k is the number of letters in w • Usually each word is associated with addition info – not discussed here. 2 Trie (Tree+Retrive) for S A trie - example p->ar[‘b’-’a’] Note: The label of an edge is the label of n A tree where each node is a struct consist the cell from which this edge exits n Struct node { p a b c d n char[4] *ar; 0 a n char flag ; /* 1 if a word ends at this node. b d Otherwise 0 */ a b c d a b c d Corresponding to w=“d” } a b c d a b c d flag 1 1 0 ar 1 b Corr. To w=“db” (not in S, flag=0) S={a,b,dbb} a b c d 0 a b c d flag ar 1 b Rule: a b c d Corr. to w= dbb Each node corresponds to a word w 1 “ ” (w which is in S iff the flag is 1) 3 In S, so flag=1 4 1 Finding if word w is in the tree Inserting a word w p=root; i =0 Recall – we need to modify the tree so find(w) would return While(1){ TRUE. n If w[i] == ‘\0’ // we scanned all letters of w n then return the flag of p ; // True/False n If the entry of p correspond to w[i] is NULL return false; nTry to perform find(w). n Set p to be the node pointed by this entry, and set i++; n If runs into a NULL pointers, create new node(s) along } the path. n The flag fields of all new node(s) is 0. nSet the flag of the last node to 1 5 6 Inserting “cbb” Deleting a word w Note: The label of an edge is the label of p->ar[‘b’-’a’] the cell from which this edge exits n Find the node p corresponding to w (using `find’ p a b c d 0 operation). a b d a b c d a b c d n Set the flag field of p to 0. a b c d a b c d Corr. to w=“d” 1 1 0 0 S={a,b,dbb, cbb} b b n If p is dead (I.e. flag==0 and all pointers are NULL ) Try to perform find(cbb). then free(p), set p=parent(p) and repeat this check. a b c d a b c d Corr. to w=“db” If runs into a NULL pointers, create w=“cb” 0 0 new node(s) along the path. The flag fields of all new node(s)=0. b b Set the flag of the last node to 1 a b c d Corr. to w=“dbb” 1 a b c d In S, so flag=1 7 w=“cbb” 1 7 8 2 Space requirements Heuristics for space saving n Let m be is the sum of characters of all words in S n To save some space, if Σ is larger, there are a few n The space required might be Θ( |Σ | m ) heuristics we can use. Assume Σ={a,b..z} . n (for each letter of each words of S, we need an array of size n We use two types of nodes |Σ | n Type “A”, which is used when the number of children of a (Might be an issue by itself, and might slow down node is more than 3 performances) a b z flag type a b z flag p p Note – the letters are not stores explicit ally Note – the letters are not stores explicit ally 9 10 Heuristics for space saving Another Heuristics – path compression n Replace a long sequence of nodes that a b c d n Type “B” is used if there are 3 or less children: happens to have only a single child, with n The “letter” of the child is also stored: a single node (of type “pointer to string”) a b c d that keeps a point to the next node, and a point to a string. a b c d type letter pointer letter pointer letter pointer flag p a b c d B F R a b c d type a b c d “bbac\0” • The rule of the flag is the same as in type “A” nodes. • We only store the 3 pointers, but we need to know to which letters they corresponds to 11 3 Suffix tree. Suffix tree. n Assume B (for book) is a long text. Example B=“aabab” S={“aabab”, “abab”, “bab”, “ab”, “b”} n Want to preprocess B, so when a word w is given, we could a b c d quickly find if it is in B. (incremental search) n (as well as locations, how many etc) a b c d a b c d 1 n We can find it in O(|w|). a b c d a b c d a b c d n Idea: 1 n Consider B as a long string. To know where a word a b c d a b c d a b c d appear in B, we store with n Create a trie T of all suffixes of B. 1 each node the index of the beginning of the suffix in B. n In addition to the flag (specifying if a word ends at node), a b c d a b c d we also stored the index in B where this word begins. 1 (we can store only the first appearance of the word in n Example B=“aabab” a b c d the text) S={“aabab”, “abab”, “bab”, “ab”, “b”} 13 1 14 Size of suffix tree Size of suffix tree 12345 Example B=“aabab” S={“aabab”, “abab”, “bab”, “ab”, “b”} Example B=“aabab” S={“aabab”, “abab”, “bab”, “ab”, “b”} a b c d 1 a b c d Assume n=|B|. Assume n=|B|. 1 Total length of all string Θ(n2) a b c d a b c d Total length of all string Θ(n2) a b c d a b c d 3 1 1 Size of a node is |Σ| Size of a node is |Σ| 1 2 a b c d a b c d a b c d a b c d a b c d a b c d 3 So size of the tree is Θ(n2 |Σ| ). 1 So size of the tree is Θ(n2 |Σ| ). 1 2 a b c d a b c d a b c d 1 a b c d a b c d a b c d 3 2 1 2 1 Time to construct the tree Θ(n ) Time to construct the tree Θ(n ) 2 a b c d a b c d 1 a b c d a b c d 1 1 a b c d 1 a b c d Rather than a flag, we store the 1 In addition to the flag, we store 1 first index where the suffix Example B=“aabab” the first index (in the book) Example B=“aabab” appear S={“aabab”, “abab”, “bab”, “ab”, “b”} where the suffix starts (in red) S={“aabab”, “abab”, “bab”, “ab”, “b”} 15 16 4 Suffix tries on a diet Suffix tries on a diet - cont a b c d a b c d Def: a shred is a path from node u to node v in the Algorithm for constructing a “thin” trie: trie, consisting of nodes of outdegree 1 (except a b c d a b c d maybe the last one) and flag=0. Given B – create an empty trie T, and insert all n Obs: There is a contiguous part of B, identical to the a b c d suffixes of B into T --- generating a trie of size a b c d string the shred represents. We call this part the Θ(n2). shred-string a b c d a b c d We stores B itself as an array. Traverse the tries, and each time that a shred is We use a new type of nodes, called shred-nodes, a b c d seen, replace all nodes of the shred with a a b c d that maintain only the indexes of the first (id1) single shred-node. and last (id2) letters of the shred-string in B. type a b c d id1 id2 flag 7 10 1 7 10 Example for shred of “adbd” B=“cadbdaadbd 17 18 Suffix tries on a diet - cont a b c d a b c d Clearly the use of shred nodes saves some-but n can we prove something ? a b c d Thanks for patience. Observations: The # number of leaves of T is a b c d at most ≤ n n See you at the review (every leaf is the end of one prefix).
Recommended publications
  • Application of TRIE Data Structure and Corresponding Associative Algorithms for Process Optimization in GRID Environment
    Application of TRIE data structure and corresponding associative algorithms for process optimization in GRID environment V. V. Kashanskya, I. L. Kaftannikovb South Ural State University (National Research University), 76, Lenin prospekt, Chelyabinsk, 454080, Russia E-mail: a [email protected], b [email protected] Growing interest around different BOINC powered projects made volunteer GRID model widely used last years, arranging lots of computational resources in different environments. There are many revealed problems of Big Data and horizontally scalable multiuser systems. This paper provides an analysis of TRIE data structure and possibilities of its application in contemporary volunteer GRID networks, including routing (L3 OSI) and spe- cialized key-value storage engine (L7 OSI). The main goal is to show how TRIE mechanisms can influence de- livery process of the corresponding GRID environment resources and services at different layers of networking abstraction. The relevance of the optimization topic is ensured by the fact that with increasing data flow intensi- ty, the latency of the various linear algorithm based subsystems as well increases. This leads to the general ef- fects, such as unacceptably high transmission time and processing instability. Logically paper can be divided into three parts with summary. The first part provides definition of TRIE and asymptotic estimates of corresponding algorithms (searching, deletion, insertion). The second part is devoted to the problem of routing time reduction by applying TRIE data structure. In particular, we analyze Cisco IOS switching services based on Bitwise TRIE and 256 way TRIE data structures. The third part contains general BOINC architecture review and recommenda- tions for highly-loaded projects.
    [Show full text]
  • Compressed Suffix Trees with Full Functionality
    Compressed Suffix Trees with Full Functionality Kunihiko Sadakane Department of Computer Science and Communication Engineering, Kyushu University Hakozaki 6-10-1, Higashi-ku, Fukuoka 812-8581, Japan [email protected] Abstract We introduce new data structures for compressed suffix trees whose size are linear in the text size. The size is measured in bits; thus they occupy only O(n log |A|) bits for a text of length n on an alphabet A. This is a remarkable improvement on current suffix trees which require O(n log n) bits. Though some components of suffix trees have been compressed, there is no linear-size data structure for suffix trees with full functionality such as computing suffix links, string-depths and lowest common ancestors. The data structure proposed in this paper is the first one that has linear size and supports all operations efficiently. Any algorithm running on a suffix tree can also be executed on our compressed suffix trees with a slight slowdown of a factor of polylog(n). 1 Introduction Suffix trees are basic data structures for string algorithms [13]. A pattern can be found in time proportional to the pattern length from a text by constructing the suffix tree of the text in advance. The suffix tree can also be used for more complicated problems, for example finding the longest repeated substring in linear time. Many efficient string algorithms are based on the use of suffix trees because this does not increase the asymptotic time complexity. A suffix tree of a string can be constructed in linear time in the string length [28, 21, 27, 5].
    [Show full text]
  • KP-Trie Algorithm for Update and Search Operations
    The International Arab Journal of Information Technology, Vol. 13, No. 6, November 2016 722 KP-Trie Algorithm for Update and Search Operations Feras Hanandeh1, Izzat Alsmadi2, Mohammed Akour3, and Essam Al Daoud4 1Department of Computer Information Systems, Hashemite University, Jordan 2, 3Department of Computer Information Systems, Yarmouk University, Jordan 4Computer Science Department, Zarqa University, Jordan Abstract: Radix-Tree is a space optimized data structure that performs data compression by means of cluster nodes that share the same branch. Each node with only one child is merged with its child and is considered as space optimized. Nevertheless, it can’t be considered as speed optimized because the root is associated with the empty string. Moreover, values are not normally associated with every node; they are associated only with leaves and some inner nodes that correspond to keys of interest. Therefore, it takes time in moving bit by bit to reach the desired word. In this paper we propose the KP-Trie which is consider as speed and space optimized data structure that is resulted from both horizontal and vertical compression. Keywords: Trie, radix tree, data structure, branch factor, indexing, tree structure, information retrieval. Received January 14, 2015; accepted March 23, 2015; Published online December 23, 2015 1. Introduction the exception of leaf nodes, nodes in the trie work merely as pointers to words. Data structures are a specialized format for efficient A trie, also called digital tree, is an ordered multi- organizing, retrieving, saving and storing data. It’s way tree data structure that is useful to store an efficient with large amount of data such as: Large data associative array where the keys are usually strings, bases.
    [Show full text]
  • Lecture 26 Fall 2019 Instructors: B&S Administrative Details
    CSCI 136 Data Structures & Advanced Programming Lecture 26 Fall 2019 Instructors: B&S Administrative Details • Lab 9: Super Lexicon is online • Partners are permitted this week! • Please fill out the form by tonight at midnight • Lab 6 back 2 2 Today • Lab 9 • Efficient Binary search trees (Ch 14) • AVL Trees • Height is O(log n), so all operations are O(log n) • Red-Black Trees • Different height-balancing idea: height is O(log n) • All operations are O(log n) 3 2 Implementing the Lexicon as a trie There are several different data structures you could use to implement a lexicon— a sorted array, a linked list, a binary search tree, a hashtable, and many others. Each of these offers tradeoffs between the speed of word and prefix lookup, amount of memory required to store the data structure, the ease of writing and debugging the code, performance of add/remove, and so on. The implementation we will use is a special kind of tree called a trie (pronounced "try"), designed for just this purpose. A trie is a letter-tree that efficiently stores strings. A node in a trie represents a letter. A path through the trie traces out a sequence ofLab letters that9 represent : Lexicon a prefix or word in the lexicon. Instead of just two children as in a binary tree, each trie node has potentially 26 child pointers (one for each letter of the alphabet). Whereas searching a binary search tree eliminates half the words with a left or right turn, a search in a trie follows the child pointer for the next letter, which narrows the search• Goal: to just words Build starting a datawith that structure letter.
    [Show full text]
  • Suffix Trees
    JASS 2008 Trees - the ubiquitous structure in computer science and mathematics Suffix Trees Caroline L¨obhard St. Petersburg, 9.3. - 19.3. 2008 1 Contents 1 Introduction to Suffix Trees 3 1.1 Basics . 3 1.2 Getting a first feeling for the nice structure of suffix trees . 4 1.3 A historical overview of algorithms . 5 2 Ukkonen’s on-line space-economic linear-time algorithm 6 2.1 High-level description . 6 2.2 Using suffix links . 7 2.3 Edge-label compression and the skip/count trick . 8 2.4 Two more observations . 9 3 Generalised Suffix Trees 9 4 Applications of Suffix Trees 10 References 12 2 1 Introduction to Suffix Trees A suffix tree is a tree-like data-structure for strings, which affords fast algorithms to find all occurrences of substrings. A given String S is preprocessed in O(|S|) time. Afterwards, for any other string P , one can decide in O(|P |) time, whether P can be found in S and denounce all its exact positions in S. This linear worst case time bound depending only on the length of the (shorter) string |P | is special and important for suffix trees since an amount of applications of string processing has to deal with large strings S. 1.1 Basics In this paper, we will denote the fixed alphabet with Σ, single characters with lower-case letters x, y, ..., strings over Σ with upper-case or Greek letters P, S, ..., α, σ, τ, ..., Trees with script letters T , ... and inner nodes of trees (that is, all nodes despite of root and leaves) with lower-case letters u, v, ...
    [Show full text]
  • Efficient In-Memory Indexing with Generalized Prefix Trees
    Efficient In-Memory Indexing with Generalized Prefix Trees Matthias Boehm, Benjamin Schlegel, Peter Benjamin Volk, Ulrike Fischer, Dirk Habich, Wolfgang Lehner TU Dresden; Database Technology Group; Dresden, Germany Abstract: Efficient data structures for in-memory indexing gain in importance due to (1) the exponentially increasing amount of data, (2) the growing main-memory capac- ity, and (3) the gap between main-memory and CPU speed. In consequence, there are high performance demands for in-memory data structures. Such index structures are used—with minor changes—as primary or secondary indices in almost every DBMS. Typically, tree-based or hash-based structures are used, while structures based on prefix-trees (tries) are neglected in this context. For tree-based and hash-based struc- tures, the major disadvantages are inherently caused by the need for reorganization and key comparisons. In contrast, the major disadvantage of trie-based structures in terms of high memory consumption (created and accessed nodes) could be improved. In this paper, we argue for reconsidering prefix trees as in-memory index structures and we present the generalized trie, which is a prefix tree with variable prefix length for indexing arbitrary data types of fixed or variable length. The variable prefix length enables the adjustment of the trie height and its memory consumption. Further, we introduce concepts for reducing the number of created and accessed trie levels. This trie is order-preserving and has deterministic trie paths for keys, and hence, it does not require any dynamic reorganization or key comparisons. Finally, the generalized trie yields improvements compared to existing in-memory index structures, especially for skewed data.
    [Show full text]
  • Search Trees
    Lecture III Page 1 “Trees are the earth’s endless effort to speak to the listening heaven.” – Rabindranath Tagore, Fireflies, 1928 Alice was walking beside the White Knight in Looking Glass Land. ”You are sad.” the Knight said in an anxious tone: ”let me sing you a song to comfort you.” ”Is it very long?” Alice asked, for she had heard a good deal of poetry that day. ”It’s long.” said the Knight, ”but it’s very, very beautiful. Everybody that hears me sing it - either it brings tears to their eyes, or else -” ”Or else what?” said Alice, for the Knight had made a sudden pause. ”Or else it doesn’t, you know. The name of the song is called ’Haddocks’ Eyes.’” ”Oh, that’s the name of the song, is it?” Alice said, trying to feel interested. ”No, you don’t understand,” the Knight said, looking a little vexed. ”That’s what the name is called. The name really is ’The Aged, Aged Man.’” ”Then I ought to have said ’That’s what the song is called’?” Alice corrected herself. ”No you oughtn’t: that’s another thing. The song is called ’Ways and Means’ but that’s only what it’s called, you know!” ”Well, what is the song then?” said Alice, who was by this time completely bewildered. ”I was coming to that,” the Knight said. ”The song really is ’A-sitting On a Gate’: and the tune’s my own invention.” So saying, he stopped his horse and let the reins fall on its neck: then slowly beating time with one hand, and with a faint smile lighting up his gentle, foolish face, he began..
    [Show full text]
  • Lecture 1: Introduction
    Lecture 1: Introduction Agenda: • Welcome to CS 238 — Algorithmic Techniques in Computational Biology • Official course information • Course description • Announcements • Basic concepts in molecular biology 1 Lecture 1: Introduction Official course information • Grading weights: – 50% assignments (3-4) – 50% participation, presentation, and course report. • Text and reference books: – T. Jiang, Y. Xu and M. Zhang (co-eds), Current Topics in Computational Biology, MIT Press, 2002. (co-published by Tsinghua University Press in China) – D. Gusfield, Algorithms for Strings, Trees, and Sequences: Computer Science and Computational Biology, Cambridge Press, 1997. – D. Krane and M. Raymer, Fundamental Concepts of Bioin- formatics, Benjamin Cummings, 2003. – P. Pevzner, Computational Molecular Biology: An Algo- rithmic Approach, 2000, the MIT Press. – M. Waterman, Introduction to Computational Biology: Maps, Sequences and Genomes, Chapman and Hall, 1995. – These notes (typeset by Guohui Lin and Tao Jiang). • Instructor: Tao Jiang – Surge Building 330, x82991, [email protected] – Office hours: Tuesday & Thursday 3-4pm 2 Lecture 1: Introduction Course overview • Topics covered: – Biological background introduction – My research topics – Sequence homology search and comparison – Sequence structural comparison – string matching algorithms and suffix tree – Genome rearrangement – Protein structure and function prediction – Phylogenetic reconstruction * DNA sequencing, sequence assembly * Physical/restriction mapping * Prediction of regulatiory elements • Announcements:
    [Show full text]
  • Search Trees for Strings a Balanced Binary Search Tree Is a Powerful Data Structure That Stores a Set of Objects and Supports Many Operations Including
    Search Trees for Strings A balanced binary search tree is a powerful data structure that stores a set of objects and supports many operations including: Insert and Delete. Lookup: Find if a given object is in the set, and if it is, possibly return some data associated with the object. Range query: Find all objects in a given range. The time complexity of the operations for a set of size n is O(log n) (plus the size of the result) assuming constant time comparisons. There are also alternative data structures, particularly if we do not need to support all operations: • A hash table supports operations in constant time but does not support range queries. • An ordered array is simpler, faster and more space efficient in practice, but does not support insertions and deletions. A data structure is called dynamic if it supports insertions and deletions and static if not. 107 When the objects are strings, operations slow down: • Comparison are slower. For example, the average case time complexity is O(log n logσ n) for operations in a binary search tree storing a random set of strings. • Computing a hash function is slower too. For a string set R, there are also new types of queries: Lcp query: What is the length of the longest prefix of the query string S that is also a prefix of some string in R. Prefix query: Find all strings in R that have S as a prefix. The prefix query is a special type of range query. 108 Trie A trie is a rooted tree with the following properties: • Edges are labelled with symbols from an alphabet Σ.
    [Show full text]
  • Suffix Trees for Fast Sensor Data Forwarding
    Suffix Trees for Fast Sensor Data Forwarding Jui-Chieh Wub Hsueh-I Lubc Polly Huangac Department of Electrical Engineeringa Department of Computer Science and Information Engineeringb Graduate Institute of Networking and Multimediac National Taiwan University [email protected], [email protected], [email protected] Abstract— In data-centric wireless sensor networks, data are alleviates the effort of node addressing and address reconfig- no longer sent by the sink node’s address. Instead, the sink uration in large-scale mobile sensor networks. node sends an explicit interest for a particular type of data. The source and the intermediate nodes then forward the data Forwarding in data-centric sensor networks is particularly according to the routing states set by the corresponding interest. challenging. It involves matching of the data content, i.e., This data-centric style of communication is promising in that it string-based attributes and values, instead of numeric ad- alleviates the effort of node addressing and address reconfigura- dresses. This content-based forwarding problem is well studied tion. However, when the number of interests from different sinks in the domain of publish-subscribe systems. It is estimated increases, the size of the interest table grows. It could take 10s to 100s milliseconds to match an incoming data to a particular in [3] that the time it takes to match an incoming data to a interest, which is orders of mangnitude higher than the typical particular interest ranges from 10s to 100s milliseconds. This transmission and propagation delay in a wireless sensor network. processing delay is several orders of magnitudes higher than The interest table lookup process is the bottleneck of packet the propagation and transmission delay.
    [Show full text]
  • X-Fast and Y-Fast Tries
    x-Fast and y-Fast Tries Outline for Today ● Bitwise Tries ● A simple ordered dictionary for integers. ● x-Fast Tries ● Tries + Hashing ● y-Fast Tries ● Tries + Hashing + Subdivision + Balanced Trees + Amortization Recap from Last Time Ordered Dictionaries ● An ordered dictionary is a data structure that maintains a set S of elements drawn from an ordered universe � and supports these operations: ● insert(x), which adds x to S. ● is-empty(), which returns whether S = Ø. ● lookup(x), which returns whether x ∈ S. ● delete(x), which removes x from S. ● max() / min(), which returns the maximum or minimum element of S. ● successor(x), which returns the smallest element of S greater than x, and ● predecessor(x), which returns the largest element of S smaller than x. Integer Ordered Dictionaries ● Suppose that � = [U] = {0, 1, …, U – 1}. ● A van Emde Boas tree is an ordered dictionary for [U] where ● min, max, and is-empty run in time O(1). ● All other operations run in time O(log log U). ● Space usage is Θ(U) if implemented deterministically, and O(n) if implemented using hash tables. ● Question: Is there a simpler data structure meeting these bounds? The Machine Model ● We assume a transdichotomous machine model: ● Memory is composed of words of w bits each. ● Basic arithmetic and bitwise operations on words take time O(1) each. ● w = Ω(log n). A Start: Bitwise Tries Tries Revisited ● Recall: A trie is a simple data 0 1 structure for storing strings. 0 1 0 1 ● Integers can be thought of as strings of bits. 1 0 1 1 0 ● Idea: Store integers in a bitwise trie.
    [Show full text]
  • Tries and String Matching
    Tries and String Matching Where We've Been ● Fundamental Data Structures ● Red/black trees, B-trees, RMQ, etc. ● Isometries ● Red/black trees ≡ 2-3-4 trees, binomial heaps ≡ binary numbers, etc. ● Amortized Analysis ● Aggregate, banker's, and potential methods. Where We're Going ● String Data Structures ● Data structures for storing and manipulating text. ● Randomized Data Structures ● Using randomness as a building block. ● Integer Data Structures ● Breaking the Ω(n log n) sorting barrier. ● Dynamic Connectivity ● Maintaining connectivity in an changing world. String Data Structures Text Processing ● String processing shows up everywhere: ● Computational biology: Manipulating DNA sequences. ● NLP: Storing and organizing huge text databases. ● Computer security: Building antivirus databases. ● Many problems have polynomial-time solutions. ● Goal: Design theoretically and practically efficient algorithms that outperform brute-force approaches. Outline for Today ● Tries ● A fundamental building block in string processing algorithms. ● Aho-Corasick String Matching ● A fast and elegant algorithm for searching large texts for known substrings. Tries Ordered Dictionaries ● Suppose we want to store a set of elements supporting the following operations: ● Insertion of new elements. ● Deletion of old elements. ● Membership queries. ● Successor queries. ● Predecessor queries. ● Min/max queries. ● Can use a standard red/black tree or splay tree to get (worst-case or expected) O(log n) implementations of each. A Catch ● Suppose we want to store a set of strings. ● Comparing two strings of lengths r and s takes time O(min{r, s}). ● Operations on a balanced BST or splay tree now take time O(M log n), where M is the length of the longest string in the tree.
    [Show full text]