If you have had the chance to study computer science, you may have come across graphs, which are very important data structures in computer science as they represent the relationship between objects. Whether you’re diving into open coding interviews or practicing new algorithms on sites such as LeetCode, it is vital to know how directed graphs work is vital. As a result, this blog will show how to approach such problems by showing how to make directed graph in Python leetcode efficiently.
In this article, we’ll explore:
- What is a directed graph?
- Why directed graphs are handy in problem-solving
- How to represent a directed graph in Python
- Examples of LeetCode problems involving directed graphs
- Python code implementation for directed graphs
- Best practices and tips for graph-related coding interviews
Let’s dive into the details!
What is a Directed Graph?
A digraph is often referred to as a directed graph and if is composed of nodes or vertices and directed edges. While, an undirected graph shows the two nodes have a connection from one node to the other and vice versa in an equally strong connection, a directed graph represents a one-way connection. This feature makes directed graphs ideal to be used in real-life problems such as traffic flow patterns, various scheduling applications, and social media platforms.
Key Terms:
- Node/Vertex: Represents a point in the graph.
- Edge: A connection from one node to another.
- Directed Edge: An edge that points from one node to another in a specific direction.
- Cycle: A path that starts and ends at the same node.
Why Directed Graphs are Important in Problem-Solving
But graphs, especially directed graphs are of tremendous importance while modeling and solving various problems existing in artificial intelligence, biology, computer networks, and so on. In competitive programming, directed graphs help solve problems such as:
- Detecting cycles
- Shortest path calculations
- Task scheduling and dependency management
- Finding strongly connected components
Many LeetCode problems revolve around graph algorithms, making it essential to know how to make directed graph in Python LeetCode.

Representing a Directed Graph in Python
There are multiple ways to represent a directed graph in Python. The most common methods are:
- Adjacency List
- Adjacency Matrix
- Edge List
1. Adjacency List Representation
In graphs, the adjacency list is usually defined in a few lists or dictionaries; as in each node, there will be reference to other nodes or the list of nodes it points to through directed edges. This method is convenient for structures with low density as the number of edges is less than the number of nodes and the connections between them.
# Example of a Directed Graph using an Adjacency List in Python
graph = {
0: [1, 2], # Node 0 has edges directed towards Node 1 and Node 2
1: [2], # Node 1 has an edge directed towards Node 2
2: [0], # Node 2 has an edge directed towards Node 0
3: [2] # Node 3 has an edge directed towards Node 2
}
# Printing the graph representation
print(graph)
2. Adjacency Matrix Representation
Wherever a node i is connected with the node j in the network, in the matrix defined as adjacency of a property-two dimensional matrix, that entry within the parentheses i, j will become 1; otherwise it will be 0. This method is also space-consuming particularly for sparse graph but they make it easier to test if two nodes are connected
# Example of a Directed Graph using an Adjacency Matrix in Python
nodes = 4
adj_matrix = [[0] * nodes for _ in range(nodes)]
# Adding directed edges
adj_matrix[0][1] = 1
adj_matrix[0][2] = 1
adj_matrix[1][2] = 1
adj_matrix[2][0] = 1
adj_matrix[3][2] = 1
# Printing the adjacency matrix
for row in adj_matrix:
print(row)
3. Edge List Representation
An edge list or a list of all edges is simply a list of all the edges in taking the format of a graph. But every edge can be represented simply as the pair (u, v ) where u is a start vertex, and v is the end vertex. It is also helpful in the case of algorithms that work with edges, for example, Kruskal’s algorithm.
# Example of a Directed Graph using an Edge List in Python
edges = [(0, 1), (0, 2), (1, 2), (2, 0), (3, 2)]
# Printing the edge list
print(edges)
LeetCode Problems Involving Directed Graphs
LeetCode features numerous problems that require an understanding of directed graphs. Here are some common problems where you can apply your knowledge of how to make directed graph in Python LeetCode:
1. Course Schedule (LeetCode #207)
This problem concerns with the decision of whether it is feasible to finish all courses considering their dependencies. In the first case, we assume a directed graph as the prerequisite and the problem of that directed graph is to find a cycle.
from collections import defaultdict
def canFinish(numCourses, prerequisites):
graph = defaultdict(list)
for u, v in prerequisites:
graph[v].append(u)
visited = [0] * numCourses
def dfs(node):
if visited[node] == 1:
return False
if visited[node] == 2:
return True
visited[node] = 1
for neighbor in graph[node]:
if not dfs(neighbor):
return False
visited[node] = 2
return True
for course in range(numCourses):
if not dfs(course):
return False
return True
# Example usage:
numCourses = 4
prerequisites = [(1, 0), (2, 1), (3, 2)]
print(canFinish(numCourses, prerequisites)) # Output: True
2. Alien Dictionary (LeetCode #269)
This problem requires constructing a directed graph from a sorted list of words. The edges represent the ordering of characters in an alien language.
from collections import defaultdict, deque
def alienOrder(words):
graph = defaultdict(set)
indegree = {char: 0 for word in words for char in word}
for i in range(len(words) - 1):
word1, word2 = words[i], words[i + 1]
minLength = min(len(word1), len(word2))
for j in range(minLength):
if word1[j] != word2[j]:
if word2[j] not in graph[word1[j]]:
graph[word1[j]].add(word2[j])
indegree[word2[j]] += 1
break
else:
if len(word1) > len(word2):
return ""
queue = deque([char for char in indegree if indegree[char] == 0])
result = []
while queue:
char = queue.popleft()
result.append(char)
for neighbor in graph[char]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
queue.append(neighbor)
if len(result) != len(indegree):
return ""
return "".join(result)
# Example usage:
words = ["wrt", "wrf", "er", "ett", "rftt"]
print(alienOrder(words)) # Output: "wertf"
Best Practices for Graph Problems on LeetCode
- Understand the Problem: Carefully read the problem and understand the relationship between nodes and edges.
- Choose the Right Representation: Depending on the problem, choose the appropriate graph representation (adjacency list, matrix, or edge list).
- Cycle Detection: If the problem involves dependency or scheduling, think of cycle detection in directed graphs.
Table: Comparison of Graph Representations
Representation | Memory Usage | Suitable For | Time Complexity (Edge Check) |
Adjacency List | O(V + E) | Sparse graphs | O(V) |
Adjacency Matrix | O(V^2) | Dense graphs | O(1) |
Edge List | O(E) | Graph traversal algorithms | O(E) |
Mastering how to make directed graph in Python LeetCode is essential for solving numerous graph-related problems, and this guide provides a comprehensive starting point!
Summary
In For this blog, I also showed how to make directed graph in python leetcode, and also give examples of LeetCode problems involving different forms of graph representations. With the Python code snippets and best practices shared, you should now have a clearer understanding of implementing directed graphs in Python and applying them to solve various LeetCode problems efficiently.
Leave a Reply