Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

The city with the fewest neighbours within reach

Medium · Target 20 minutes · Graphs · Type asked atAmazonGoogle

There are n cities numbered 0 to n − 1. Each triple [u, v, w] in edges is a two-way road of length w. A city can reach another if the shortest route between them is at most distanceThreshold.

Return the city that can reach the fewest other cities. If several cities tie, return the one with the largest number.

Examples

InputOutputWhy
n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 43Cities 0 and 3 each reach two others; 3 is the larger number.
n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 20City 0 reaches only city 1.
n = 3, edges = [], distanceThreshold = 102No city reaches any other; the tie goes to the largest number.

Constraints

  • 2 ≤ n ≤ 100
  • 0 ≤ edges.length ≤ n(n − 1)/2
  • 1 ≤ w, distanceThreshold ≤ 10⁴

Hints

Hint 1

You need the shortest distance between every pair of cities. With n ≤ 100, Floyd–Warshall is the simplest way.

Hint 2

Roads are two-way: set both d[u][v] and d[v][u].

Hint 3

Scan cities in increasing order and replace the answer whenever a count is less than or equal to the best so far: that settles ties in favour of the larger number.

Where people lose marks

  • Treating roads as one-way.
  • Counting the city itself among its reachable neighbours.
  • Breaking ties towards the smaller city number with a strict comparison.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.