VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-sink-nodes-graph/

⇱ Number of sink nodes in a graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of sink nodes in a graph

Last Updated : 23 Jul, 2025

Given a Directed Acyclic Graph of n nodes (numbered from 1 to n) and m edges. The task is to find the number of sink nodes. A sink node is a node such that no edge emerges out of it.

Examples:

Input: n = 4, m = 2
Edges[] = {{2, 3}, {4, 3}}
Output: 2
Explanation: Only node 1 and node 3 are sink nodes.

👁 Number-of-sink-nodes-in-a-graph


Input: n = 4, m = 2
Edges[] = {{3, 2}, {3, 4}}
Output: 3

Approach

The idea is to iterate through all the edges. And for each edge, mark the source node from which the edge emerged out. Now, for each node check if it is marked or not. And count the unmarked nodes. 

Algorithm: 


1. Make any array A[] of size equal to the
number of nodes and initialize to 1.
2. Traverse all the edges one by one, say,
u -> v.
(i) Mark A[u] as 1.
3. Now traverse whole array A[] and count
number of unmarked nodes.

Output:

2

Time Complexity: O(m + n) where n is number of nodes and m is number of edges.
Space complexity : O(n) because it uses an array of size n to store the non-sink nodes.

Related Article:
The Celebrity Problem

Comment
Article Tags:
Article Tags: