VOOZH about

URL: https://www.geeksforgeeks.org/dsa/finding-in-and-out-degrees-of-all-vertices-in-a-graph/

⇱ Find Indegree and Outdegree for all vertices - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Indegree and Outdegree for all vertices

Last Updated : 28 Oct, 2025

Given a directed graph represented by its adjacency list adj[][], determine the in-degree (number of incoming edges) and out-degree (number of outgoing edges) for every vertex in the graph.

Examples:

Input: adj[][]= [[1], [], [1, 6], [2], [3, 2], [4, 6], []]

👁 topological_sorting_using_dfs_

Output: [[0, 1], [2, 0],[2, 2], [1, 1], [1, 2], [0, 2], [2, 0]]
Explanation:
Vertex 0 has 0 incoming and 1 outgoing edge.
Vertex 1 has 2 incoming and 0 outgoing edge.
Vertex 2 has 2 incoming and 2 outgoing edge.
Vertex 3 has 1 incoming and 1 outgoing edge.
Vertex 4 has 1 incoming and 2 outgoing edges.
Vertex 5 has 0 incoming and 2 outgoing edge.
Vertex 6 has 2 incoming and 0 outgoing edge.

Approach:

The main idea is to calculate the in-degree and out-degree of each vertex by traversing the adjacency list. The out-degree of a vertex i is equal to the number of vertices present in its adjacency list adj[i], and for the in-degree, we increment the count for each vertex j that has an incoming edge from the current vertex i by one.


Output
Vertex	In	Out
0	0	1
1	2	0
2	2	2
3	1	1
4	1	2
5	0	2
6	2	0

Time Complexity: O(V + E) where V and E are the numbers of vertices and edges in the graph respectively.
Auxiliary Space: O(V + E).  

Comment
Article Tags: