data structures algorithms35 min

Graphs

Networks of connected nodes for modeling relationships

0/9Not Started

Why This Matters

The world is full of connections. Friends on social media, cities linked by roads, web pages linked by hyperlinks, and tasks that depend on other tasks. A graph is the data structure that models all of these. Unlike arrays (linear) or trees (hierarchical), graphs can represent any relationship between any set of things.

When you use a GPS to find the shortest route, that is a graph algorithm at work. When a package manager resolves dependencies, it walks a graph. When a social network suggests "people you may know," it analyzes a graph. Understanding graphs unlocks an entire class of problems that no other data structure can handle.

Define Terms

Visual Model

A
B
C
D
E
F
5

The full process at a glance. Click Start tour to walk through each step.

A graph: vertices connected by edges. Weighted edges enable shortest-path algorithms.

Code Example

Code
// Graph as an adjacency list (undirected)
class Graph {
  constructor() {
    this.adjacencyList = {};
  }

  addVertex(vertex) {
    if (!this.adjacencyList[vertex]) {
      this.adjacencyList[vertex] = [];
    }
  }

  addEdge(v1, v2) {
    // Undirected: add both directions
    this.adjacencyList[v1].push(v2);
    this.adjacencyList[v2].push(v1);
  }

  getNeighbors(vertex) {
    return this.adjacencyList[vertex] || [];
  }

  display() {
    for (const vertex in this.adjacencyList) {
      console.log(vertex + " -> " + this.adjacencyList[vertex].join(", "));
    }
  }
}

const g = new Graph();
["A", "B", "C", "D"].forEach(v => g.addVertex(v));
g.addEdge("A", "B");
g.addEdge("A", "C");
g.addEdge("B", "D");
g.addEdge("C", "D");
g.display();
// A -> B, C
// B -> A, D
// C -> A, D
// D -> B, C

Interactive Experiment

Try these exercises:

  • Add a new vertex "E" and connect it to "A" and "D". Print the graph — does the structure make sense?
  • Modify the addEdge method to create a directed graph (only add one direction). What changes?
  • Try creating a graph that represents a simple road network between 5 cities you know.
  • What happens if you add the same edge twice? How could you prevent duplicates?

Quick Quiz

Coding Challenge

Path Exists

Write a function called `hasPath` that takes an adjacency list (object), a source vertex, and a destination vertex. Return `true` if there is any path from source to destination, `false` otherwise. Use any traversal approach. The graph is undirected.

Loading editor...

Real-World Usage

Graphs power some of the most critical systems in technology:

  • Social networks: Facebook, LinkedIn, and Twitter model users and relationships as graphs. Friend suggestions use graph traversal algorithms.
  • Maps and navigation: Google Maps represents intersections as vertices and roads as weighted edges. Dijkstra's algorithm finds the shortest route.
  • Dependency management: npm, pip, and other package managers build a dependency graph to determine install order and detect circular dependencies.
  • Web crawlers: Search engines model the web as a directed graph of pages linked by hyperlinks, using graph traversal to discover and index content.
  • Recommendation engines: Netflix and Spotify use graph-based algorithms to find connections between users, content, and preferences.

Connections