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 < b
  • incident(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,2]
💡 Note: Node degrees: [1,2,2,1]. For query=2: pairs (1,2)=3, (1,3)=3, (2,4)=3 all > 2, so answer=3. For query=3: pairs (1,3)=3, (2,4)=3 equal 3 but not > 3, only (1,2)=3-1=2 ≤ 3 and (3,4)=2+1=3 ≤ 3, so answer=2.
Example 2 — Multiple Edges
$ Input: n = 3, edges = [[1,2],[1,2],[2,3]], queries = [3,4]
Output: [2,1]
💡 Note: Node degrees: [2,3,1]. For query=3: pairs (1,2): incident=2+3-2=3 ≤ 3, (1,3)=2+1=3 ≤ 3, (2,3)=3+1-1=3 ≤ 3. Wait - recalculate: (1,3)=3, (2,3)=4 > 3, (1,2)=3 ≤ 3. Answer=2.
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 ≤ 1, so answer=0. Wait - incident should be > query, so 1 > 1 is false. Let me recalculate: incident = 1+1 = 2, since we count edges connected to either node. So 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
Count Pairs of Nodes: incident(a,b) > query1234deg=1deg=2deg=2deg=1Example: incident(1,3) = degree[1] + degree[3] = 1 + 2 = 3For query = 2: count pairs where incident > 2Valid pairs: (1,2)=3, (1,3)=3, (2,4)=3 → Answer = 3Goal: Efficiently count valid pairs for each query
Understanding the Visualization
1
Input Graph
Graph with n nodes and edges, plus queries
2
Calculate incident(a,b)
For each pair, count edges connected to either node
3
Count Valid Pairs
Count pairs where incident > query threshold
Key Takeaway
🎯 Key Insight: Sort node degrees and use two pointers to count pairs efficiently, avoiding O(n²) brute force per query
Asked in
Google 12 Facebook 8
18.5K Views
Medium Frequency
~35 min Avg. Time
486 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen