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
[ "wrt", "wrf", "er", "ett", "rftt" ]
Execution steps
- Infer precedence from first differing character
- Emit next available character
Computed output
"wertf"
JavaScript reference implementation
const solve = (words,s)=>{
let chars=[...new Set(words.join(""))],a=new Map(chars.map(c=>[c,new Set])),d=new Map(chars.map(c=>[c,0]));
for(let i=1;
i<words.length;
i++){
let x=words[i-1],y=words[i],j=0;
while(j<Math.min(x.length,y.length)&&x[j]===y[j])j++;
if(j===Math.min(x.length,y.length)){
if(x.length>y.length)return "";
continue
}
if(!a.get(x[j]).has(y[j])){
a.get(x[j]).add(y[j]);
d.set(y[j],d.get(y[j])+1)
}
s("Infer precedence from first differing character",{
Words:words,Edges:[...a].flatMap(([u,vs])=>[...vs].map(v=>[u,v])),Indegree:[...d]
})
}
let q=chars.filter(c=>!d.get(c)),o="";
while(q.length){
let u=q.shift();
o+=u;
for(let v of a.get(u)){
d.set(v,d.get(v)-1);
if(!d.get(v))q.push(v)
}
s("Emit next available character",{
Queue:q,Output:[...o],Indegree:[...d]
})
}
return o.length===chars.length?o:""
};