Workspace Cheapest Flights Within K Stops
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Cheapest Flights Within K Stops visualizer

Learn Cheapest Flights Within K Stops with a step-by-step Graphs visualizer, JavaScript source code and a worked example. Practice topological sorting and shortest paths.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 3Execution step
Reference example · JavaScript
Inspect reference input
{
  "n": 4,
  "edges": [
    [
      0,
      1,
      100
    ],
    [
      1,
      2,
      100
    ],
    [
      2,
      3,
      100
    ],
    [
      0,
      2,
      500
    ],
    [
      1,
      3,
      600
    ]
  ],
  "k": 1
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
n,edges,k
},s)=>{
let d=Array(n).fill(Infinity);
d[0]=0;
for(let i=0;
i<=k;
i++){
let next=d.slice();
for(let [u,v,w] of edges)next[v]=Math.min(next[v],d[u]+w);
d=next;
s("Relax using one additional flight",{
Edges:edges,Distance:d.map(x=>Number.isFinite(x)?x:null),Flights:[i+1]
})
}
return Number.isFinite(d[n-1])?d[n-1]:-1
};

Execution canvas

Active Changed
STEP 1

Relax using one additional flight

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Edges5 rows
1001001005006000123Select a node to inspect its connections.
Distance4 items
Flights1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

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,
      100
    ],
    [
      1,
      2,
      100
    ],
    [
      2,
      3,
      100
    ],
    [
      0,
      2,
      500
    ],
    [
      1,
      3,
      600
    ]
  ],
  "k": 1
}

Execution steps

  1. Relax using one additional flight

Computed output

600
JavaScript reference implementation
const solve = ({
  n,edges,k
},s)=>{
  let d=Array(n).fill(Infinity);
  d[0]=0;
  for(let i=0;
  i<=k;
  i++){
    let next=d.slice();
    for(let [u,v,w] of edges)next[v]=Math.min(next[v],d[u]+w);
    d=next;
    s("Relax using one additional flight",{
      Edges:edges,Distance:d.map(x=>Number.isFinite(x)?x:null),Flights:[i+1]
    })
  }
  return Number.isFinite(d[n-1])?d[n-1]:-1
};

Continue learning

Practice related DSA questions in the same topic.