Overview of Graph, Trie, Segment Tree and Suffix Tree Data Structures
Last Updated :
23 Jul, 2025
Introduction:
- Graph: A graph is a collection of vertices (nodes) and edges that represent relationships between the vertices. Graphs are used to model and analyze networks, such as social networks or transportation networks.
- Trie: A trie, also known as a prefix tree, is a tree-like data structure that stores a collection of strings. It is used for efficient searching and retrieval of strings, especially in the case of a large number of strings.
- Segment Tree: A segment tree is a tree-like data structure that stores information about ranges of values. It is used for range queries and range updates, such as finding the sum of an array or finding the minimum or maximum value in an array.
- Suffix Tree: A suffix tree is a tree-like data structure that stores all suffixes of a given string. It is used for efficient string search and pattern matching, such as finding the longest repeated substring or the longest common substring.
We have discussed below data structures in the previous two sets. Set 1: Overview of Array, Linked List, Queue and Stack. Set 2: Overview of Binary Tree, BST, Heap and Hash. 9. Graph 10. Trie 11. Segment Tree 12. Suffix Tree
Graph: Graph is a data structure that consists of the following two components:
- A finite set of vertices is also called nodes.
- A finite set of ordered pairs of the form (u, v) is called an edge. The pair is ordered because (u, v) is not the same as (v, u) in the case of a directed graph(di-graph). The pair of forms (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain weight/value/cost.
V -> Number of Vertices. E -> Number of Edges. The graph can be classified on the basis of many things, below are the two most common classifications :
- Direction: Undirected Graph: The graph in which all the edges are bidirectional.Directed Graph: The graph in which all the edges are unidirectional.
- Weight: Weighted Graph: The Graph in which weight is associated with the edges.Unweighted Graph: The Graph in which there is no weight associated with the edges.
Algorithm to implement graph -
The general algorithmic steps to implement a graph data structure:
- Create a class for the graph: Start by creating a class that represents the graph data structure. This class should contain variables or data structures to store information about the vertices and edges in the graph.
- Represent vertices: Choose a data structure to represent the vertices in the graph. For example, you could use an array, linked list, or dictionary.
- Represent edges: Choose a data structure to represent the edges in the graph. For example, you could use an adjacency matrix or an adjacency list.
- Add vertices: Implement a method to add vertices to the graph. You should store information about the vertex, such as its name or identifier.
- Add edges: Implement a method to add edges between vertices in the graph. You should store information about the edge, such as its weight or direction.
- Search for vertices: Implement a method to search for a specific vertex in the graph.
- Search for edges: Implement a method to search for a specific edge in the graph.
- Remove vertices: Implement a method to remove vertices from the graph.
- Remove edges: Implement a method to remove edges from the graph.
- Traverse the graph: Implement a method to traverse the graph and visit each vertex. You could use algorithms like depth-first search or breadth-first search.
This algorithm provides a basic structure for implementing a graph data structure in any programming language. You can adjust the implementation to meet the specific needs of your application.
Graphs can be represented in many ways, below are the two most common representations: Let us take the below example graph to see two representations of the graph.

Adjacency Matrix Representation of the above graph
Adjacency List Representation of the above GraphTime Complexities in case of Adjacency Matrix :
Traversal :(By BFS or DFS) O(V^2)
Space : O(V^2)
Time Complexities in case of Adjacency List :
Traversal :(By BFS or DFS) O(V + E)
Space : O(V+E)
Examples: The most common example of the graph is to find the shortest path in any network. Used in google maps or bing. Another common use application of graphs is social networking websites where the friend suggestion depends on the number of intermediate suggestions and other things.
Trie
Trie is an efficient data structure for searching words in dictionaries, search complexity with Trie is linear in terms of word (or key) length to be searched. If we store keys in a binary search tree, a well-balanced BST will need time proportional to M * log N, where M is the maximum string length and N is the number of keys in the tree. Using trie, we can search the key in O(M) time. So it is much faster than BST. Hashing also provides word search in O(n) time on average. But the advantages of Trie are there are no collisions (like hashing) so the worst-case time complexity is O(n). Also, the most important thing is Prefix Search. With Trie, we can find all words beginning with a prefix (This is not possible with Hashing). The only problem with Tries is they require a lot of extra space. Tries are also known as radix trees or prefix trees.
The Trie structure can be defined as follows :
struct trie_node
{
int value; /* Used to mark leaf nodes */
trie_node_t *children[ALPHABET_SIZE];
};
root
/ \ \
t a b
| | |
h n y
| | \ |
e s y e
/ | |
i r w
| | |
r e e
|
r
The leaf nodes are in blue.
Insert time : O(M) where M is the length of the string.
Search time : O(M) where M is the length of the string.
Space : O(ALPHABET_SIZE * M * N) where N is number of
keys in trie, ALPHABET_SIZE is 26 if we are
only considering upper case Latin characters.
Deletion time: O(M)
Algorithm to implement tree -
Here is a general algorithmic step to implement a tree data structure:
- Create a class for the tree: Start by creating a class that represents the tree data structure. This class should contain variables or data structures to store information about the nodes in the tree.
- Represent nodes: Choose a data structure to represent the nodes in the tree. For example, you could use an array, linked list, or dictionary.
- Add nodes: Implement a method to add nodes to the tree. You should store information about the node, such as its value or identifier.
- Add relationships: Implement a method to add relationships between nodes in the tree. For example, you could define a parent-child relationship between nodes.
- Search for nodes: Implement a method to search for a specific node in the tree.
- Remove nodes: Implement a method to remove nodes from the tree.
- Traverse the tree: Implement a method to traverse the tree and visit each node. You could use algorithms like in-order, pre-order, or post-order traversal.
This algorithm provides a basic structure for implementing a tree data structure in any programming language. You can adjust the implementation to meet the specific needs of your application.
Example: The most common use of Tries is to implement dictionaries due to prefix search capability. Tries are also well suited for implementing approximate matching algorithms, including those used in spell checking. It is also used for searching Contact from Mobile Contact list OR Phone Directory.
Segment Tree
This data structure is usually implemented when there are a lot of queries on a set of values. These queries involve minimum, maximum, sum, .. etc on an input range of a given set. Queries also involve updating values in the given set. Segment Trees are implemented using an array. 
Construction of segment tree : O(N)
Query : O(log N)
Update : O(log N)
Space : O(N) [Exact space = 2*N-1]
Example: It is used when we need to find the Maximum/Minimum/Sum/Product of numbers in a range.
Suffix Tree
The suffix tree is mainly used to search for a pattern in a text. The idea is to preprocess the text so that the search operation can be done in time linear in terms of pattern length. The pattern searching algorithms like KMP, Z, etc take time proportional to text length. This is really a great improvement because the length of the pattern is generally much smaller than the text. Imagine we have stored the complete work of William Shakespeare and preprocessed it. You can search any string in the complete work in time just proportional to the length of the pattern. But using Suffix Tree may not be a good idea when text changes frequently like text editor, etc. A suffix tree is a compressed trie of all suffixes, so the following are very abstract steps to build a suffix tree from given text. 1) Generate all suffixes of the given text. 2) Consider all suffixes as individual words and build a compressed trie.
Example: Used to find all occurrences of the pattern in a string. It is also used to find the longest repeated substring (when the text doesn't change often), the longest common substring and the longest palindrome in a string.
Graphs:
Advantages:
- Represent complex relationships: Graphs can be used to represent complex relationships between objects, making it a suitable data structure for many real-world scenarios.
- Efficient searching: Graphs can be searched efficiently using algorithms like depth-first search and breadth-first search.
- Flexibility: Graphs can be easily modified by adding or removing vertices and edges, making them a flexible data structure.
- Supports weighted edges: Graphs can support weighted edges, which is useful when representing relationships with different levels of importance or cost.
- Can represent directed and undirected relationships: Graphs can represent both directed and undirected relationships, making it a versatile data structure.
- Model real-world relationships and connections
- Allow for efficient searching and navigation through the network
- Can handle large and complex datasets
Disadvantages:
- Space complexity: Storing the information about vertices and edges in a graph can be memory-intensive.
- More complex algorithms: The algorithms used to traverse a graph and search for specific vertices or edges can be more complex than other data structures like arrays or linked lists.
- Slower operations: Operations like adding or removing vertices or edges can be slower than with other data structures.
- Difficult to implement: Implementing a graph data structure can be more difficult than other data structures, requiring a good understanding of graph theory and algorithms.
- May not be suitable for some use cases: For certain use cases, a graph data structure may not be the best option and another data structure like an array or linked list may be more suitable.
- May require significant computational resources
- Finding the optimal path between nodes can be a challenging problem
Tries:
Advantages:
- Fast search and retrieval of strings
- Space-efficient storage of strings
- Can be used for text processing tasks such as spell-checking
Disadvantages:
- Can have a high memory overhead for large datasets
- Insertions and deletions can be slow and complex
Segment Trees:
Advantages:
- Efficient range queries and updates
- Can handle large and complex datasets
- Can be used for a variety of range-based problems
Disadvantages:
- Can require significant memory overhead
- The creation of the tree can be a time-consuming process
Suffix Trees:
Advantages:
- Fast string search and pattern matching
- Can handle large and complex datasets
- Can be used for a variety of string-based problems
Disadvantages:
- Can have a high memory overhead
- The creation of the tree can be a time-consuming process
- Not suitable for all string-based problems, such as regular expression matching.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem