Worked example and algorithm walkthrough
Topic: Graphs · MST, DSU and advanced
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
[
[
"John",
"a@x",
"b@x"
],
[
"John",
"b@x",
"c@x"
],
[
"Mary",
"m@x"
]
]Execution steps
- Union accounts sharing email
Computed output
[
[
"John",
"a@x",
"b@x",
"c@x"
],
[
"Mary",
"m@x"
]
]JavaScript reference implementation
const solve = (a,s)=>{
let d=dsu(a.length),owner=new Map;
for(let i=0;
i<a.length;
i++)for(let e of a[i].slice(1)){
if(owner.has(e))d.union(i,owner.get(e));
else owner.set(e,i);
s("Union accounts sharing email",{
Accounts:a,Parents:d.p,Emails:[...owner]
})
}
let m=new Map;
for(let [e,i] of owner){
let r=d.find(i);
if(!m.has(r))m.set(r,[]);
m.get(r).push(e)
}
return [...m].sort((a,b)=>a[0]-b[0]).map(([i,e])=>[a[i][0],...e.sort()])
};
function adj(n,edges,directed=false){
let a=Array.from({
length:n
},()=>[]);
for(let [u,v,w=1] of edges){
a[u].push([v,w]);
if(!directed)a[v].push([u,w])
}
return a
}
function dsu(n){
let p=Array.from({
length:n
},(_,i)=>i),z=p.map(()=>1);
function find(x){
while(p[x]!==x){
p[x]=p[p[x]];
x=p[x]
}
return x
}
function union(a,b){
a=find(a);
b=find(b);
if(a===b)return false;
if(z[a]<z[b])[a,b]=[b,a];
p[b]=a;
z[a]+=z[b];
return true
}
return {
p,z,find,union
}
}
const dirs=[[1,0],[-1,0],[0,1],[0,-1]];