Back to questionsDSA Visualizers: 388 Coding Questions Find the City With Fewest Neighbors visualizer Learn Find the City With Fewest Neighbors with a step-by-step Graphs visualizer, JavaScript source code and a worked example. Practice topological sorting and shortest paths.
INTERACTIVE EXECUTION STUDIOLEARN BY DOING Predict. Execute. Understand. Follow the source code, inspect live state changes, and predict the next operation before revealing it.
1 / 6 Execution step
Prediction modePanel width Reference example · JavaScript
Inspect reference input {
"n": 4,
"edges": [
[
0,
1,
3
],
[
1,
2,
2
],
[
1,
3,
4
],
[
2,
3,
1
]
],
"threshold": 4
} Code Visuals
JavaScript reference implementation · highlighted trace statement
1 const solve = ({
2 n,edges,threshold
3 },s)=>{
4 let d=Array.from ({
5 length:n
6 },(_,i)=>Array.from ({
7 length:n
8 },(_,j)=>i===j?0 :Infinity));
9 for (let [u,v,w] of edges)d[u][v]=d[v][u]=w;
10 for (let k=0 ;
11 k<n;
12 k++){
13 for (let i=0 ;
14 i<n;
15 i++)for (let j=0 ;
16 j<n;
17 j++)d[i][j]=Math.min(d[i][j],d[i][k]+d[k][j]);
18 s("Allow intermediate vertex "+k,{
19 Distance:d.map(r=>r.map(x=>Number.isFinite(x)?x:null)),Intermediate:[k]
20 })
21 }
22 let c=d.map((r,i)=>r.filter((v,j)=>i!==j&&v<=threshold).length);
23 s("Count neighbors within threshold; prefer largest index on tie",{
24 Counts:c
25 });
26 return c.lastIndexOf(Math.min(...c))
27 };
Execution canvas Active ChangedSTEP 1 Allow intermediate vertex 0 Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.
Worked example and algorithm walkthrough Topic: Graphs · Topological sorting and shortest paths
Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.
Example input {
"n": 4,
"edges": [
[
0,
1,
3
],
[
1,
2,
2
],
[
1,
3,
4
],
[
2,
3,
1
]
],
"threshold": 4
} Execution steps Allow intermediate vertex 0 Allow intermediate vertex 1 Allow intermediate vertex 2 Allow intermediate vertex 3 Count neighbors within threshold; prefer largest index on tie Computed output 0 JavaScript reference implementation const solve = ({
n,edges,threshold
},s)=>{
let d=Array.from({
length:n
},(_,i)=>Array.from({
length:n
},(_,j)=>i===j?0:Infinity));
for(let [u,v,w] of edges)d[u][v]=d[v][u]=w;
for(let k=0;
k<n;
k++){
for(let i=0;
i<n;
i++)for(let j=0;
j<n;
j++)d[i][j]=Math.min(d[i][j],d[i][k]+d[k][j]);
s("Allow intermediate vertex "+k,{
Distance:d.map(r=>r.map(x=>Number.isFinite(x)?x:null)),Intermediate:[k]
})
}
let c=d.map((r,i)=>r.filter((v,j)=>i!==j&&v<=threshold).length);
s("Count neighbors within threshold; prefer largest index on tie",{
Counts:c
});
return c.lastIndexOf(Math.min(...c))
};Continue learning Practice related DSA questions in the same topic.