DSA interview question
A delivery company picks a new warehouse city. For each city it counts how many other cities are reachable within a distance threshold, and it wants the city with the fewest such neighbours (the most isolated, so the hub serves an under-covered area). Ties go to the city with the greatest index. All pairs of distances are needed, so run Floyd–Warshall, then count per city.
Example: n = 4, edges 0-1 (3), 1-2 (1), 1-3 (4), 2-3 (1), threshold 4 → 3.
int findTheCity(int n, const vector<array<int, 3>>& edges, int distanceThreshold); // undirected
Input (n, edges, threshold) | Output | Explanation |
|---|---|---|
(4, [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], 4) | 3 | Cities 0 and 3 both have 2 neighbours; 3 is larger |
(5, [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], 2) | 0 | City 0 has only 1 neighbour |
(3, [[0,1,1],[1,2,1]], 1) | 2 | Cities 0 and 2 tie with 1 neighbour |
(2, [[0,1,5]], 4) | 1 | Neither reaches the other |
(3, [], 5) | 2 | Everyone has 0 neighbours |
(Confirm: edges are undirected and weighted; "within the threshold" means distance ≤ threshold; ties choose the greatest index.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in