792. Busiest City Pair

Medium3.5 points estimatedGraphCounting3 hints

A transport planner studies n cities numbered 0 to n - 1 and two-way roads given as [a, b] pairs in roads. For two different cities, the load of the pair is the number of roads that touch at least one of the two cities; a road that joins the two cities directly is counted once.

Return the largest load over all pairs of different cities. If there are no roads, return 0. No two roads join the same pair of cities and no road starts and ends in the same city.

Example 1

Input:
n = 6, roads = [[5,2],[2,0],[2,1],[3,4]]
Output:
4
Explanation:

City 2 has 3 roads and city 3 is not linked to it, so the pair (2, 3) touches 3 + 1 = 4 roads, and no other pair does better.

Example 2

Input:
n = 7, roads = [[6,0],[0,1],[1,2],[2,6],[6,3],[4,5]]
Output:
5
Explanation:

Cities 6 and 1 are not directly linked, so their roads add up fully: 3 + 2 = 5.

Example 3

Input:
n = 2, roads = [[0,1]]
Output:
1
Explanation:

Only one road exists and it touches both cities.

Constraints

  • 2 ≤ n ≤ 105
  • 0 ≤ roads.length ≤ 2 * 105
  • 0 ≤ a, b < n and a ≠ b; each unordered pair appears at most once

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 300 msC++ 75 msJava 150 msJavaScript 150 msTypeScript 150 ms

Expected complexity

Time
O((n + m) log n)
Space
O(n + m)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…