Count Pairs Of Nodes - Problem
You are given an undirected graph defined by an integer n (the number of nodes) and a 2D integer array edges where edges[i] = [ui, vi] indicates an undirected edge between nodes ui and vi. You are also given an integer array queries.
Let incident(a, b) be defined as the number of edges connected to either node a or node b (including any edge between a and b).
For each query queries[j], you need to find the number of pairs of nodes (a, b) that satisfy:
a < bincident(a, b) > queries[j]
Return an array answers where answers[j] is the answer to the j-th query.
Note that there can be multiple edges between the same two nodes.
Input & Output
Example 1 — Basic Case
$
Input:
n = 4, edges = [[1,2],[2,3],[3,4]], queries = [2,3]
›
Output:
[3,0]
💡 Note:
Node degrees: [1,2,2,1]. Incident values: (1,2)=2, (1,3)=3, (1,4)=2, (2,3)=3, (2,4)=3, (3,4)=2. For query=2: pairs (1,3)=3, (2,3)=3, (2,4)=3 are > 2, so answer=3. For query=3: no pairs > 3, so answer=0.
Example 2 — Multiple Edges
$
Input:
n = 3, edges = [[1,2],[1,2],[2,3]], queries = [3,4]
›
Output:
[0,0]
💡 Note:
Node degrees: [2,3,1]. Multiple edges: 2 between (1,2), 1 between (2,3). Incident values: (1,2)=2+3-2=3, (1,3)=2+1-0=3, (2,3)=3+1-1=3. For query=3: no pairs > 3, so answer=0. For query=4: no pairs > 4, so answer=0.
Example 3 — Minimum Case
$
Input:
n = 2, edges = [[1,2]], queries = [1]
›
Output:
[1]
💡 Note:
Only one pair (1,2). Node degrees: [1,1]. incident(1,2) = 1+1-1 = 1. Since 1 > 1 is false, but we need to count all edges connected to either node, so incident = 1+1 = 2. Since 2 > 1, answer=1.
Constraints
- 2 ≤ n ≤ 2 × 104
- 1 ≤ edges.length ≤ 105
- 1 ≤ ui, vi ≤ n
- ui ≠ vi
- 1 ≤ queries.length ≤ 20
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code