Kazi Rahamatullah
Kazi Rahamatullah
AboutProjectsBlogContact
UsesBooks
ResumeView CV
Kazi Rahamatullah

© Copyright 2026 Kazi Rahamatullah

AboutProjectsBlogBooksUses
Twitter/XGitHubProduct HuntCodeSandbox
Back to Blog
DSAGraphsData Structures

DSA Graphs — Fundamentals Visualized

Learn graph fundamentals — vertices, edges, directed vs undirected, weighted graphs, interactive visualizer, and real-world network examples.

Jul 4, 20264 min read

Introduction

Graphs model relationships — unlike trees (one parent per node), graphs allow arbitrary connections, cycles, and multiple paths between vertices.

Social networks, road maps, dependency graphs, and the web are all graphs.

Quick index

#Section
1How graphs work
2Interactive visualizer
3Full implementation
4Graph types
5vs trees
6Real-life examples

1. How graphs work

plaintext
        A
       / \
      B   C
     / \   \
    D   E   F

A graph G = (V, E) has a set of vertices V and edges E connecting them.

TermMeaning
Vertex (node)An entity — user, city, web page
Edge (link)A connection between two vertices
DegreeNumber of edges touching a vertex
PathSequence of edges connecting two vertices
CyclePath that starts and ends at the same vertex

Back to index


2. Interactive visualizer

Graphs — Fundamentals

Vertices and edges model networks — social graphs, maps, dependencies, and the web.

A
B
C
D
E
F

A graph G = (V, E) — vertices (nodes) connected by edges (links).

Graph basics

// V = { A, B, C, D, E, F }
// E = { A-B, A-C, B-D, B-E, C-F }

const graph = {
  A: ["B", "C"],
  B: ["A", "D", "E"],
  C: ["A", "F"],
  // ...
}

Unlike trees, graphs can have cycles and multiple paths between nodes.

Vertices

6

Edges

5

Space

O(V+E)

Tip

Unlike trees, graphs can have cycles and multiple paths between the same two nodes.

Back to index


3. Full implementation

js
class Graph {
  constructor(directed = false) {
    this.adj = new Map()
    this.directed = directed
  }
 
  addVertex(v) {
    if (!this.adj.has(v)) this.adj.set(v, [])
  }
 
  addEdge(a, b, weight = 1) {
    this.addVertex(a)
    this.addVertex(b)
    this.adj.get(a).push({ to: b, weight })
    if (!this.directed) this.adj.get(b).push({ to: a, weight })
  }
 
  getNeighbors(v) {
    return this.adj.get(v) ?? []
  }
 
  hasEdge(a, b) {
    return this.getNeighbors(a).some((e) => e.to === b)
  }
 
  degree(v) {
    return this.getNeighbors(v).length
  }
 
  vertexCount() {
    return this.adj.size
  }
}
 
function buildSampleGraph() {
  const g = new Graph(false)
  ;['A', 'B', 'C', 'D', 'E', 'F'].forEach((v) => g.addVertex(v))
  g.addEdge('A', 'B')
  g.addEdge('A', 'C')
  g.addEdge('B', 'D')
  g.addEdge('B', 'E')
  g.addEdge('C', 'F')
  return g
}

Function calls with output

js
// ── Demo calls — output shown on the right ──
const g = buildSampleGraph()
 
g.vertexCount() // → 6
g.getNeighbors('A') // → [{ to:'B', weight:1 }, { to:'C', weight:1 }]
g.degree('B') // → 3
g.hasEdge('A', 'C') // → true
g.hasEdge('D', 'F') // → false

Back to index


4. Graph types

TypeEdgesExample
UndirectedTwo-wayFacebook friends
DirectedOne-wayTwitter follows
WeightedCost on edgeGPS distance
UnweightedAll equalWeb page links
CyclicHas a cycleCircular dependency
Acyclic (DAG)No cyclesBuild pipeline

Back to index


5. vs trees

StructureConnectionsCyclesRoot
TreeParent → childrenNoYes (single)
GraphAny vertex to anyYesNo

Interview Answer

"When would you use a graph over a tree?"

When relationships are not hierarchical — mutual friendships, bidirectional roads, or web links where any page can link to any other. Trees are a special case of graphs (connected, acyclic, with a root).

Back to index


6. Real-life examples

ScenarioGraph role
Social networkUsers = vertices, friendships = edges
Google MapsIntersections = vertices, roads = weighted edges
npm dependenciesPackages = vertices, requires = directed edges
Web crawlingPages = vertices, hyperlinks = directed edges

Social network friend graph

Users are vertices, friendships are edges — mutual connections form an undirected graph.

Aliceid:1[0]
Bobid:2[1]

Each user becomes a vertex in the graph.

Real-world implementation

class SocialGraph {
  constructor() { this.adj = new Map() }
  addUser(id) { if (!this.adj.has(id)) this.adj.set(id, new Set()) }
  addFriendship(a, b) {
    this.addUser(a); this.addUser(b)
    this.adj.get(a).add(b)
    this.adj.get(b).add(a)
  }
  friendsOf(id) { return [...(this.adj.get(id) ?? [])] }
  mutualFriends(a, b) {
    const fa = this.adj.get(a) ?? new Set()
    return [...(this.adj.get(b) ?? [])].filter(f => fa.has(f))
  }
}

Full working code for the scenario above.

Function calls with output

// ── Function calls with output ──
const net = new SocialGraph()
net.addUser("Alice"); net.addUser("Bob")→ 2 vertices

Side output shows return value after each call — step through to trace execution.

Back to index


Summary

Graphs model arbitrary relationships — vertices and edges with optional direction and weight. Next: how to store them efficiently.

Next reads: Graphs Implementation · Graph Traversal

Share this article

XLinkedInFacebook
Kazi Rahamatullah

Written by

Kazi Rahamatullah

FullStack Developer

X / TwitterGitHubLinkedIn

Subscribe to my newsletter

Stay up to date and get notified when I share new contents.

No spam ever, unsubscribe anytime