Find the City With the Smallest Number of Neighbors

35 min · findTheCity()

A city wants the quietest hub: the place with the fewest nearby neighbors by road distance, not by the number of direct roads.

You receive n cities numbered from 0 through n - 1. Each [u, v, w] in edges is an undirected edge — a road that can be used both ways and has length w.

For each city, count how many other cities can be reached with a shortest-route distance no greater than distanceThreshold. Return the city with the smallest count. When several cities share that count, return the one with the greatest index.

Roads don't connect a city to itself, and each unordered pair appears at most once. The graph may be disconnected.

Constraints

  • 2 <= n <= 100
  • 0 <= edges.length <= n * (n - 1) / 2
  • Every edges[i] is [u, v, w] with 0 <= u, v < n, u != v, and 1 <= w <= 10_000.
  • No undirected city pair appears twice.
  • 0 <= distanceThreshold <= 10_000

Hints

Direct roads aren't enough

A city may be within the threshold through several roads. You need shortest-path distances between every pair of cities, not just the edges you were given.

Think all-pairs

Build an n × n distance table: zero on the diagonal, road weights where edges exist, and infinity elsewhere. Then try every city as an allowed middle stop.

Let the tie rule shape the loop

Scan cities from smallest to largest and replace the answer when a count is less than or equal to the best count. Equality then naturally keeps the larger index.

Follow-up

If n were huge but the road map were sparse, would running a single-source algorithm from each city become more attractive than an n × n table?

Visible cases

Examples

Example 1

ready
Input
n = 4
edges = [
  [
    0,
    1,
    3
  ],
  [
    1,
    2,
    1
  ],
  [
    1,
    3,
    4
  ],
  [
    2,
    3,
    1
  ]
]
distanceThreshold = 4
Expected
3
Why
city 3 reaches two neighbors; ties favor the greatest index

Example 2

ready
Input
n = 5
edges = [
  [
    0,
    1,
    2
  ],
  [
    0,
    4,
    8
  ],
  [
    1,
    2,
    3
  ],
  [
    1,
    4,
    2
  ],
  [
    2,
    3,
    1
  ],
  [
    3,
    4,
    1
  ]
]
distanceThreshold = 2
Expected
0
Why
only city 1 is within distance 2 of city 0

Example 3

ready
Input
n = 2
edges = [
  [
    0,
    1,
    3
  ]
]
distanceThreshold = 3
Expected
1
Why
both cities reach one neighbor, so city 1 wins the tie

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite