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?- A. 4
- B. 3
- C. 0
- 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
- Problem: Count all paths from node 0 to node n − 1 in a DAG (memoised DFS). python from functools import lrucache g = {0: [1, 2, 3], 1…
- Problem: Rebuild a binary tree from its inorder and postorder traversals (distinct values) and print its preorder. python def prefrom(ino…
- Problem: Lowest common ancestor in a general binary tree (not a BST), with the recursive 'return whichever side found something' method…
- Problem: Delete the nodes with given values from a binary tree and return the roots of the remaining forest, sorted. python class T: def…
- Problem: Print the boundary of a binary tree anticlockwise: root, left boundary (excluding leaves), all leaves left to right, then the…
- Problem: Convert a BST so each node's value becomes the sum of all values ≥ it (reverse inorder with a running sum); print the new…