Represent directed and undirected graphs
Quick answer
A graph represents vertices and edges. An adjacency list records each vertex’s outgoing neighbors and is useful for sparse relationships such as routes or dependencies.
Working examples
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
const adj=Array.from({length:4},()=>[]);for(const [u,v] of [[0,1],[1,2]])adj[u].push(v);console.log(JSON.stringify(adj));Expected console output:
[[1],[2],[],[]]Only outgoing edges are stored; vertices 2 and 3 have no outgoing neighbors.
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
const adj=Array.from({length:3},()=>[]);for(const [u,v] of [[0,1],[1,2]]){adj[u].push(v);adj[v].push(u);}console.log(JSON.stringify(adj),adj[2].includes(1));Expected console output:
[[1],[0,2],[1]] trueBoth directions are recorded for each undirected edge.
How it works and cost model
For vertex IDs 0 through V-1, create V independent arrays. Directed edge [u,v] adds v to adj[u]; an undirected edge adds both directions, with a defined policy for self-loops and duplicates. Include vertices with no neighbors. A list stores O(V+E) entries for a directed graph (twice the edge entries for an undirected graph); an adjacency matrix stores V² cells but allows direct indexed edge queries. Under the usual cost model list neighbor enumeration costs O(outdegree). Validate endpoint indices before construction. These examples preserve supplied edge order and do not treat repeated edges as distinct vertices.
Common mistakes
Do not initialize every row with Array(V).fill([]): all rows would reference the same array. Use Array.from with a new array per vertex.
Practice
Build directed and undirected adjacency lists for four vertices and edges [0,1],[1,2]. Explain the isolated vertex and what changes when direction is removed.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Represent directed and undirected graphs — Knowledge Check
Reason about the algorithm or data structure, its invariants, trade-offs and deterministic outputs.
Which structure represents a vertex with no outgoing edges in an adjacency list?
Why use Array.from({length:V},()=>[]) rather than fill([]) for rows?
How does an ordinary adjacency matrix storage size grow for V vertices?
What is the exact console output in the Graph adjacency list example 1?
const adj=Array.from({length:4},()=>[]);for(const [u,v] of [[0,1],[1,2]])adj[u].push(v);console.log(JSON.stringify(adj));What is the exact console output in the Graph adjacency list example 2?
const adj=Array.from({length:3},()=>[]);for(const [u,v] of [[0,1],[1,2]]){adj[u].push(v);adj[v].push(u);}console.log(JSON.stringify(adj),adj[2].includes(1));