Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Return the city that can reach the FEWEST other cities within a distance threshold (largest index on ties), using Floyd–Warshall.

Problem: Return the city that can reach the FEWEST other cities within a distance threshold (largest index on ties), using Floyd–Warshall.
def city(n, edges, th):
    INF = float('inf'); d = [[0 if i == j else INF for j in range(n)] for i in range(n)]
    for u, v, w in edges: d[u][v] = d[v][u] = w
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if d[i][k] + d[k][j] < d[i][j]: d[i][j] = d[i][k] + d[k][j]
    best, ans = n + 1, -1
    for i in range(n):
        c = sum(1 for j in range(n) if j != i and d[i][j] <= th)
        if c <= best: best, ans = c, i
    return ans
print(city(5, [(0,1,2),(0,4,8),(1,2,3),(1,4,2),(2,3,1),(3,4,1)], 2))
What is printed?
  1. A. 4
  2. B. 3
  3. C. 0
  4. D. 1

Correct answer: C. 0

With threshold 2: city 0 reaches only 1; city 1 reaches 0 and 4; city 2 reaches 3 and 4 (via 3, 1 + 1); city 3 reaches 2 and 4; city 4 reaches 1, 2 (via 3) and 3. City 0 is the only one reaching just one neighbour, so the answer is 0; using <= would pick the largest index if there were a tie.

More Coding Interview Problems questions

Exams that ask this topic