Count Pairs Of Nodes Problem
Description
LeetCode Problem 1782.
You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [u_i, v_i] indicates that there is an undirected edge between u_i and v_i. You are also given an integer array queries.
Let incident(a, b) be defined as the number of edges that are connected to either node a or b.
The answer to the j^th query is the number of pairs of nodes (a, b) that satisfy both of the following conditions:
a < bincident(a, b) > queries[j]
Return an array answers such that answers.length == queries.length and answers[j] is the answer of the j^th query.
Note that there can be multiple edges between the same two nodes.
Example 1:

Input: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]
Output: [6,5]
Explanation: The calculations for incident(a, b) are shown in the table above.
The answers for each of the queries are as follows:
- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.
- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.
Example 2:
Input: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]
Output: [10,10,9,8,6]
Constraints:
2 <= n <= 2 * 10^41 <= edges.length <= 10^51 <= u_i, v_i <= nu_i!= v_i1 <= queries.length <= 200 <= queries[j] < edges.length
Solution
Approach: Degrees + Sorting + Binary Search
The number of edges incident to a pair (a, b) is deg[a] + deg[b] minus the number of edges directly between a and b, because those edges are counted twice.
First count the degree of every node, and use a hash map to count the edges between each pair of nodes. Then answer each query q:
- Sort the degrees. For every node
ain this order, binary search the first later nodebwithdeg[a] + deg[b] > q; every node from there on forms a pair withawhose plain degree sum is large enough. Add them up. - Some of those pairs were counted wrongly because of the shared edges. For each pair
(a, b)witheedges between them, ifdeg[a] + deg[b] > qbutdeg[a] + deg[b] - e <= q, subtract one.
Complexity: O(q · (n log n + m)) time and O(n + m) space, where n is the number of nodes, m the number of edges and q the number of queries.
from bisect import bisect_right
from collections import defaultdict
class Solution:
def countPairs(
self, n: int, edges: List[List[int]], queries: List[int]
) -> List[int]:
cnt = [0] * n
g = defaultdict(int)
for a, b in edges:
a, b = a - 1, b - 1
a, b = min(a, b), max(a, b)
cnt[a] += 1
cnt[b] += 1
g[(a, b)] += 1
s = sorted(cnt)
ans = [0] * len(queries)
for i, t in enumerate(queries):
for j, x in enumerate(s):
k = bisect_right(s, t - x, lo=j + 1)
ans[i] += n - k
for (a, b), v in g.items():
if cnt[a] + cnt[b] > t and cnt[a] + cnt[b] - v <= t:
ans[i] -= 1
return ans