avatarNaina Chaturvedi

Summary

The provided web content is a comprehensive guide on graph data structures and algorithms, offering insights into their importance, representation, traversal methods, and practical applications through examples and projects, as part of a larger series on data structures, algorithms, and system design.

Abstract

The article "Day 19 of 30 days of Data Structures and Algorithms and System Design Simplified — Graphs" delves into the concept of graphs, a non-linear data structure consisting of nodes and edges, and their significance in various computational problems. It explains the two primary methods of graph representation: adjacency lists and adjacency matrices, and discusses the algorithms for graph traversal, including Depth First Search (DFS) and Breadth First Search (BFS). The author emphasizes the importance of understanding graph algorithms for solving complex problems and provides a detailed walkthrough of important graph patterns and techniques. The post also includes examples of graph problems, such as detecting cycles and finding the shortest path, and offers solutions with code snippets. Additionally, the article introduces a new YouTube channel, Ignito, which will feature videos on projects and coding exercises related to the content discussed. The article concludes with a list of other relevant series and resources for further learning in data science, machine learning, and system design.

Opinions

  • The author believes that graph algorithms are crucial for tackling high-complexity problems and have a very high importance in the field of computer science.
  • There is a strong emphasis on learning by doing, as evidenced by the inclusion of practical examples and the encouragement to implement solutions to understand graph algorithms better.
  • The article suggests that readers should be familiar with implementing DFS and BFS, understanding recursion, and creating adjacency matrices and lists before attempting graph questions.
  • The author advocates for regular practice and exploration of graph problems, indicating that new graph questions with solutions are added daily.
  • The introduction of the Ignito YouTube channel implies that visual and video-based learning resources can complement written tutorials effectively.
  • The author's approach to complexity analysis in graph algorithms suggests a preference for efficiency and performance optimization in problem-solving.
  • By providing a mega-compilation of solved system design case studies and other best series, the author conveys a commitment to comprehensive education and resource sharing within the tech community.

Day 19 of 30 days of Data Structures and Algorithms and System Design Simplified — Graphs

Pic credits : algorist

Welcome back peeps. Hope all’s well. In this post we will cover Graphs as follows —

What and Why Graphs(in 2–3 sentences)?

How does Graphs work?

Important Patterns and Techniques in Graphs Questions

Most Important Questions with Solutions

Complexity Analysis

Tips and Techniques to solve Graphs Questions Fast.

Projects Videos —

All the projects, data structures, SQL, algorithms, system design, Data Science and ML , Data Analytics, Data Engineering, , Implemented Data Science and ML projects, Implemented Data Engineering Projects, Implemented Deep Learning Projects, Implemented Machine Learning Ops Projects, Implemented Time Series Analysis and Forecasting Projects, Implemented Applied Machine Learning Projects, Implemented Tensorflow and Keras Projects, Implemented PyTorch Projects, Implemented Scikit Learn Projects, Implemented Big Data Projects, Implemented Cloud Machine Learning Projects, Implemented Neural Networks Projects, Implemented OpenCV Projects,Complete ML Research Papers Summarized, Implemented Data Analytics projects, Implemented Data Visualization Projects, Implemented Data Mining Projects, Implemented Natural Leaning Processing Projects, MLOps and Deep Learning, Applied Machine Learning with Projects Series, PyTorch with Projects Series, Tensorflow and Keras with Projects Series, Scikit Learn Series with Projects, Time Series Analysis and Forecasting with Projects Series, ML System Design Case Studies Series videos will be published on our youtube channel ( just launched).

Subscribe today!

System Design Case Studies — In Depth

Design Instagram

Design Messenger App

Design Twitter

Design URL Shortener

Design Dropbox

Design Youtube

Design API Rate Limiter

Design Web Crawler

Design Facebook’s Newsfeed

Design Yelp

Design Uber

Design Tinder

Design Tiktok

Design Whatsapp

Most Popular System Design Questions

Mega Compilation : Solved System Design Case studies

Graphs

Importance : Very High

Day 2 of data structures and algorithms covers the topics that are most important and with highest ROI.

Note : New Graphs questions with solutions are added every day. So keep checking this post daily.

Let’s dive in!

What is Graphs?

Graph is a non linear data structure which consists of nodes connected by the edges ( which can undirected or directed).

Graphs are represented using —

1.Adjacency List — Used when the graph is sparse

2. Adjacency Matrix — Used when the graph is dense

Adjacency List

Every node in the graph has a list of its adjacent/neighboring nodes forming an adjacency list.

Pic credits : stesting

Adjacency Matrix

Pic credits: ycpcs

Adjacency Matrix — Matrix of size n*n where n is the no of edges is filled with 1’s or 0’s based on if there’s an edge is present from respective nodes.

Examples of Graphs problems —

Detect Cycle in graph

Topological sort

Shortest path in a graph (Weighted and Unweighted)

Minimum spanning tree etc

How does Graphs work?

A graph can be represented in different ways, such as an adjacency matrix or an adjacency list. An adjacency matrix is a two-dimensional array that represents the edges between the vertices, while an adjacency list is a list of linked lists that represents the edges between the vertices.

There are two ways you can traverse the graphs to search for a node in the graphs/subgraphs. Both the ways differ by the order in which nodes are traversed.

DFS — Stack is used

BFS — Queue is used

Pic credits : neo4j

Depth First Search ( DFS)

Start the traversal from one node and subsequently do in depth traversal of the adjacent nodes by recursively calling the DFS function.

Breadth First Search ( BFS)

Start the traversal from one node and subsequently do level by level traversal of the adjacent/neighbor nodes.

Important Patterns and Techniques in Graphs Questions

Some important patterns and techniques in graph questions include:

  1. Graph traversal: This technique is used to traverse all the vertices of a graph and can be implemented using algorithms such as Breadth First Search (BFS) and Depth First Search (DFS).
  2. Shortest Path: This technique is used to find the shortest path between two vertices in a graph, using algorithms such as Dijkstra’s algorithm and Bellman-Ford algorithm.
  3. Minimum Spanning Tree: This technique is used to find the minimum spanning tree of a graph, using algorithms such as Kruskal’s algorithm and Prim’s algorithm.
  4. Strongly Connected Components: This technique is used to find the strongly connected components of a directed graph, using algorithms such as Tarjan’s algorithm and Kosaraju’s algorithm.

Most of the questions wrt graphs —

  1. Traversals
  2. Detect Cycle in the graph
  3. Island related questions
  4. Calculate area of island/square in the adjacency matrix

Most Important Questions with Solutions

Note : New Graphs questions with solutions are added every day. So keep checking this post daily.

Golden rule is — Learn by doing/implementing

In this we will see most important Graphs questions.

Clone Graph

Question —

Given a reference of a node in a connected undirected graph.

Return a deep copy (clone) of the graph.

Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.

class Node {
    public int val;
    public List<Node> neighbors;
}

Example :

Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]

Solution :

Main Logic/Idea —

The main logic is to create a copy of the nodes and then connect them same structurally by traversing through its neighbors in the adjacency list.

Implementation —

def cloneGraph(self, node: 'Node') -> 'Node':
        hMap = {}
        
        def cGraph(node):
            if node in hMap:
                return hMap[node]
            
            copy = Node(node.val)
            hMap[node] = copy
            
            for neighbor in node.neighbors:
                copy.neighbors.append(cGraph(neighbor))
            return copy
        return cGraph(node) if node else None

Question Link

Similar Pattern —

Clone Binary Tree With Random Pointer

Clone N-ary Tree

Full Code Video Explanation ( In progress. Subscribe today for updates) :

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Longest Increasing Path in a Matrix

Question —

Example 1:

Input: s = "pwwkew"
Output: 3

Solution :

Main Logic/Idea —

The main logic is to go through the matrix by performing recursive dfs ( in all the directions) and return the longest increasing path. Check for the boundary conditions at every step.

Implementation —

def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        rows, cols, temp = len(matrix), len(matrix[0]),{}
        
        
        def calcPath(r,c,previousVal):
            ans = 1
            if (r<0 or r == rows or c<0 or c==cols or matrix[r][c] <= previousVal):
                return 0
            
            if (r,c) in temp:
                return temp[(r,c)]
            
            ans = max(ans,1+calcPath(r+1,c,matrix[r][c]))
            ans = max(ans,1+calcPath(r,c+1,matrix[r][c]))
            ans = max(ans,1+calcPath(r-1,c,matrix[r][c]))
            ans = max(ans,1+calcPath(r,c-1,matrix[r][c]))
            
            temp[(r,c)] = ans
            return ans
        
        for ro in range(rows):
            for co in range(cols):
                calcPath(ro,co,-1)
        return max(temp.values())

Question Link

Similar Pattern —

Number of Increasing Paths in a Grid

Full Code Video Explanation ( In progress. Subscribe today for updates) :

Note : New Graphs questions with solutions are added every day. So keep checking this post daily.

Complexity Analysis

Before this section, read complexity analysis post.

Time complexity of BFS and DFS

Adjacency List — O(V + E)

Adjacency Matrix — O(V²)

Where E is the edges and V is the nodes.

Tips and Techniques to solve Graphs Questions Fast.

Before attempting the graph questions —

  1. Know how to implement DFS and BFS.
  2. Know how recursion works.
  3. Know how to create adjacency matrix and adjacency list.

That’s it for now. Day 20: Heap/Priority Queue coming soon !

Let me know if you have questions in the comment section below. Subscribe/ Follow, Like/Clap as it will encourage me to write more in my free time and Stay Tuned!!

Read More —

11 most important System Design Base Concepts

1. System design basics

2. Horizontal and vertical scaling

3. Load balancing and Message queues

4. High level design and low level design, Consistent Hashing, Monolithic and Microservices architecture

5. Caching, Indexing, Proxies

6. Networking, How Browsers work, Content Network Delivery ( CDN)

7. Database Sharding, CAP Theorem, Database schema Design

8. Concurrency, API, Components + OOP + Abstraction

9. Estimation and Planning, Performance

10. Map Reduce, Patterns and Microservices

11. SQL vs NoSQL and Cloud

12. Most Popular System Design Questions

13. System Design Template — How to solve any System Design Question

14. Quick RoundUp : Solved System Design Case Studies

Some of the other best Series —

60 days of Data Science and ML Series with projects

30 Days of Natural Language Processing ( NLP) Series

30 days of Machine Learning Ops

30 days of Data Structures and Algorithms and System Design Simplified

60 Days of Deep Learning with Projects Series

30 days of Data Engineering with projects Series

Data Science and Machine Learning Research ( papers) Simplified **

100 days : Your Data Science and Machine Learning Degree Series with projects

23 Data Science Techniques You Should Know

Tech Interview Series — Curated List of coding questions

Complete System Design with most popular Questions Series

Complete Data Visualization and Pre-processing Series with projects

Complete Python Series with Projects

Complete Advanced Python Series with Projects

Kaggle Best Notebooks that will teach you the most

Complete Developers Guide to Git

Exceptional Github Repos — Part 1

Exceptional Github Repos — Part 2

All the Data Science and Machine Learning Resources

210 Machine Learning Projects

Tech Newsletter —

If you are interested, you can join my newsletter through which I send tech interview tips, techniques, patterns, hacks — Software Development, ML, Data Science, Startups and Technology projects to more than 30K readers. You can subscribe to Tech Brew :

For Python Projects —

For complete 60 days of Data Science and ML : Day 1 — Day 60 : Quick Recap of 60 days of Data Science and ML

Follow for more updates. Stay tuned and keep coding!

For other projects, tune to —

Build Machine Learning Pipelines( With Code)

Recurrent Neural Network with Keras

Clustering Geolocation Data in Python using DBSCAN and K-Means

Facial Expression Recognition using Keras

Hyperparameter Tuning with Keras Tuner

Custom Layers in Keras

Programming
Software Development
Tech
Data Science
Machine Learning
Recommended from ReadMedium