709926. Number of pairs
Here is a detailed Markdown blog post for the problem:
Number of Pairs
Summary
The problem is to find the number of pairs in a graph where each node has an even degree. The key concepts involved are dynamic programming and disjoint sets.
Detailed Explanation
To solve this problem, we can use a combination of dynamic programming and disjoint sets. We will start by initializing an array dp of size n+1, where n is the number of nodes in the graph. We will also initialize a set parent to keep track of the parent of each node.
We will then iterate over each node in the graph, and for each node, we will find all its neighbors using DFS. For each neighbor, we will check if it has an even degree. If it does, we will add 1 to the count of pairs.
To avoid counting the same pair multiple times, we can use a disjoint set data structure. We will initialize each node as its own parent, and then for each edge in the graph, we will union the two nodes that the edge connects. This way, all nodes with the same connected component will be part of the same set.
Finally, we will iterate over each set and add 1 to the count of pairs for each set that has more than one node. This is because a pair can only exist between two nodes in the same set if they have an even degree.
Here is the step-by-step breakdown:
- Initialize
dparray of sizen+1 - Initialize
parentset - Iterate over each node in the graph:
- Find all neighbors using DFS
- For each neighbor, check if it has an even degree and add 1 to the count of pairs if it does
- Use disjoint sets to avoid counting the same pair multiple times
- Iterate over each set and add 1 to the count of pairs for each set that has more than one node
Time complexity: O(n) Space complexity: O(n)
Optimized Solutions
Java
int countPairs(int[][] graph) {
int n = graph.length;
boolean[] visited = new boolean[n];
List<Integer>[] parentList = new List[n];
for (int i = 0; i < n; i++) {
parentList[i] = new ArrayList<>();
parentList[i].add(i);
}
for (int i = 0; i < n; i++) {
for (int j = graph[i].length - 1; j >= 0; j--) {
int neighbor = graph[i][j];
if (!visited[neighbor]) {
visited[neighbor] = true;
parentList[neighbor].add(i);
}
}
}
int count = 0;
for (int i = 0; i < n; i++) {
if (parentList[i].size() > 1) {
count++;
}
}
return count;
}