PPractick

DSA interview question

Find the City with the Smallest Number of Neighbours at a Threshold Distance

Hard · Data structures · Topics: graph, floyd warshall

The problem

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.

Function signature

int findTheCity(int n, const vector<array<int, 3>>& edges, int distanceThreshold);  // undirected

Test cases

Input (n, edges, threshold)OutputExplanation
(4, [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], 4)3Cities 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)0City 0 has only 1 neighbour
(3, [[0,1,1],[1,2,1]], 1)2Cities 0 and 2 tie with 1 neighbour
(2, [[0,1,5]], 4)1Neither reaches the other
(3, [], 5)2Everyone has 0 neighbours

(Confirm: edges are undirected and weighted; "within the threshold" means distance ≤ threshold; ties choose the greatest index.)

How interviewers phrase it

Clarifying questions to ask

  1. Is the threshold inclusive? (Yes: ≤.)
  2. How are ties broken? (The greatest index.)
  3. How large is n? (Up to 100, so O(n³) is fine.)

Follow-ups to expect

  1. "Why Floyd–Warshall?"
  2. "Alternative?"
  3. "How do you implement the tie rule?"
  4. "Why can't BFS work?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in