Count Pairs Of Nodes — LeetCode 1782 Python Solution

HardGraphArrayHash TableTwo PointersBinary SearchCountingSorting
Problem
#1782
Reading time
4 min

The problem

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] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries.

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(q \times (n \times \log n + m))
SpaceO(n + m) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1782. Count Pairs Of Nodes is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1782. Count Pairs Of Nodes?
LeetCode 1782. Count Pairs Of Nodes is rated Hard on LeetCode.
What is the time complexity of LeetCode 1782. Count Pairs Of Nodes?
The Python solution on this page runs in O(q \times (n \times \log n + m)).
What is the space complexity of LeetCode 1782. Count Pairs Of Nodes?
The Python solution on this page uses O(n + m) auxiliary space.
What topics does LeetCode 1782. Count Pairs Of Nodes cover?
LeetCode 1782. Count Pairs Of Nodes is tagged Graph, Array, Hash Table, Two Pointers, Binary Search, Counting and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview