Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
Array Data Structure
Next article icon

Overview of Graph, Trie, Segment Tree and Suffix Tree Data Structures

Last Updated : 09 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Introduction:

  1. 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.
  2. 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.
  3. 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.
  4. 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:

  1. A finite set of vertices is also called nodes.
  2. 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 :

  1. Direction: Undirected Graph: The graph in which all the edges are bidirectional.Directed Graph: The graph in which all the edges are unidirectional.
  2. 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 Graph

Adjacency List Representation of the above Graph

Time 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.


Next Article
Array Data Structure

A

Abhiraj Smit
Improve
Article Tags :
  • Advanced Data Structure
  • DSA
  • Segment-Tree
  • Suffix-Tree
  • Trie
Practice Tags :
  • Advanced Data Structure
  • Segment-Tree
  • Trie

Similar Reads

  • Data Structures Tutorial
    Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
    2 min read
  • Introduction to Data Structures
    What is Data Structure?A data structure is a particular way of organising data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. The choice of a good data structure makes it possible to perform a variety of critical operations
    7 min read
  • Data Structure Types, Classifications and Applications
    A data structure is a storage that is used to store and organize data. It is a way of arranging data on a computer so that it can be accessed and updated efficiently. A data structure organizes, processes, retrieves, and stores data, making it essential for nearly every program or software system. T
    7 min read
  • Overview of Data Structures

    • Introduction to Linear Data Structures
      Linear Data Structures are a type of data structure in computer science where data elements are arranged sequentially or linearly. Each element has a previous and next adjacent, except for the first and last elements. Characteristics of Linear Data Structure:Sequential Organization: In linear data s
      8 min read

    • Introduction to Hierarchical Data Structure
      We have discussed Overview of Array, Linked List, Queue and Stack. In this article following Data Structures are discussed. 5. Binary Tree 6. Binary Search Tree 7. Binary Heap 8. Hashing Binary Tree Unlike Arrays, Linked Lists, Stack, and queues, which are linear data structures, trees are hierarchi
      13 min read

    • Overview of Graph, Trie, Segment Tree and Suffix Tree Data Structures
      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
      10 min read

    Different Types of Data Structures

    • Array Data Structure
      Complete Guide to ArraysLearn more about Array in DSA Self Paced CoursePractice Problems on ArraysTop Quizzes on Arrays What is Array?An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calcul
      3 min read

    • String in Data Structure
      A 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 immu
      3 min read

    • Stack Data Structure
      A 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
      3 min read

    • Queue Data Structure
      A 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

    • Linked List Data Structure
      A 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:
      3 min read

    • Introduction to Tree Data Structure
      Tree data structure is a hierarchical structure that is used to represent and organize data in the form of parent child relationship. The following are some real world situations which are naturally a tree. Folder structure in an operating system.Tag structure in an HTML (root tag the as html tag) o
      15+ min read

    • Heap Data Structure
      A Heap is a complete binary tree data structure that satisfies the heap property: for every node, the value of its children is greater than or equal to its own value. Heaps are usually used to implement priority queues, where the smallest (or largest) element is always at the root of the tree. Basic
      2 min read

    • Hashing in Data Structure
      Hashing 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
      3 min read

    • Graph Algorithms
      Graph algorithms are methods used to manipulate and analyze graphs, solving various range of problems like finding the shortest path, cycles detection. If you are looking for difficulty-wise list of problems, please refer to Graph Data Structure. BasicsGraph and its representationsBFS and DFS Breadt
      3 min read

    • Matrix Data Structure
      Matrix Data Structure is a two-dimensional array arranged in rows and columns. It is commonly used to represent mathematical matrices and is fundamental in various fields like mathematics, computer graphics, and data processing. Matrices allow for efficient storage and manipulation of data in a stru
      2 min read

    • Advanced Data Structures
      Advanced Data Structures refer to complex and specialized arrangements of data that enable efficient storage, retrieval, and manipulation of information in computer science and programming. These structures go beyond basic data types like arrays and lists, offering sophisticated ways to organize and
      3 min read

  • Data Structure Alignment : How data is arranged and accessed in Computer Memory?
    Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment. Data alignment: Data alignment means putting the data in memory at an
    4 min read
  • Static Data Structure vs Dynamic Data Structure
    Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two
    4 min read
  • Static and Dynamic Data Structures
    Data structures are the fundamental building blocks of computer programming. They determine how data is organized, stored, and manipulated within a software application. There are two main categories of data structures: static and dynamic. Static data structures have a fixed size and are allocated i
    9 min read
  • Common operations on various Data Structures
    Data Structure is the way of storing data in computer's memory so that it can be used easily and efficiently. There are different data-structures used for the storage of data. It can also be defined as a mathematical or logical model of a particular organization of data items. The representation of
    15+ min read
  • Real-life Applications of Data Structures and Algorithms (DSA)
    You may have heard that DSA is primarily used in the field of computer science. Although DSA is most commonly used in the computing field, its application is not restricted to it. The concept of DSA can also be found in everyday life. Here we'll address the common concept of DSA that we use in our d
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences