# Find the Number of Sink Nodes in a Graph using C++

In this article, we will describe the important information on solving the number of sinks nodes in a graph. We have a Directed Acyclic Graph with N nodes (1 to N) and M edges in this problem. The goal is to find how many sink nodes are there in the given graph. A sink node is a node that does not produce any outgoing edges. So here is a simple example −

Input : n = 4, m = 2

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

## Simple Approach to Find the Solution

In this approach, we will go through the edges of the graph, push distinct elements in the set from which edges are going, and then subtract the size of the set with the total number of nodes present.

## Example

#include <bits/stdc++.h>
using namespace std;
int main(){
int n = 4; // number of nodes.
int m = 2; // number of edges.
vector<pair<int, int>> edges = {{2, 3}, {4, 3}}; // the edges going from first to second.
set<int> s;
for(int i = 0; i < m; i++){
s.insert(edges[i].first); // will keep value of
// distinct node from which edges are going out.
}
cout << n - s.size(); // answer is the total number of nodes - number of non sink nodes.
return 0;
}

## Output

2

## Explanation of the Above Code

In this code, we will traverse through the vector edges and insert the first element of the pair into a set. It only keeps the distinct elements, so now we will subtract the specific size of the set from the total number of nodes. The program shown above has the time complexity of O(N) in which the N stands for the number of edges present in a graph.

## Conclusion

In this article, we solved the problem of finding the Number of sink nodes present in a graph O(N) time complexity using the help of a set. We also learned the C++ program for this problem and the complete approach by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. Hope you find this article helpful.