Problem Description
Given an undirected graph with n nodes and a list of edges (which may contain duplicate pairs), for any two distinct nodes a and b (with a < b), the "incident" score is defined as the total number of edges connected to either node including duplicates. For each query value in a set of queries, we must count the number of pairs (a, b) such that the incident count is greater than the query value.
Key Insights
- Compute the degree for each node; note that duplicate edges will increase node degrees.
- Count the number of direct connections between each unique pair (using a map or dictionary) because a and b might be connected by multiple edges.
- Sort the degree array to leverage two pointers or binary search for efficient counting.
- For any pair (a, b), the total incident count is degree[a] + degree[b] minus the number of duplicate edges between them.
- For each query, count all pairs that satisfy degree[a] + degree[b] > query initially then subtract those pairs where the direct connection count causes an overcount.
- Adjusting with the direct connection count is a critical gotcha.
Space and Time Complexity
Time Complexity: O(m + n log n + q * n) in the worst-case scenario, where m is the number of edges, n is the number of nodes, and q is the number of queries. (Note: With careful implementation and two pointers/binary search, much of the inner loop can be optimized.) Space Complexity: O(n + m), for storing the degree array and the mapping of direct edge counts.
Solution
We start by computing the degree for each node from all edges. Simultaneously, we use a hash map to count the number of direct (possibly duplicate) connections between each unique pair (ordered so that a < b). Once the degrees are computed, we sort the degree list. For each query, we use a two‐pointers technique on the sorted degrees to count the number of pairs (i, j) where degree[i] + degree[j] > query. However, some pairs might have been over-counted because of multiple direct connections between them; for each such pair, if degree[i] + degree[j] > query but degree[i] + degree[j] - directConnections <= query, we decrease the count. This ensures that only the valid pairs are counted. The result for each query is stored and returned in order.