Approach
Sorting and greedy selection
For Count Pairs Of Nodes, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 43 lines of Python from the credited upstream file 1782.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def countPairs(3 self,4 n: int,5 edges: list[list[int]],6 queries: list[int],7 ) -> list[int]:8 ans = [0] * len(queries)9 10 11 count = [0] * (n + 1)12 13 14 shared = [collections.Counter() for _ in range(n + 1)]15 16 for u, v in edges:17 count[u] += 118 count[v] += 119 shared[min(u, v)][max(u, v)] += 120 21 sortedCount = sorted(count)22 23 for k, query in enumerate(queries):24 i = 125 j = n26 while i < j:27 if sortedCount[i] + sortedCount[j] > query:28 29 30 31 32 33 ans[k] += j - i34 j -= 135 else:36 i += 137 for i in range(1, n + 1):38 for j, sh in shared[i].items():39 if count[i] + count[j] > query and count[i] + count[j] - sh <= query:40 ans[k] -= 141 42 return ans43