# Graph

> The Graph is a data structure that models relationships between entities through nodes and edges, ideal for networked data.

## What is a graph data structure and how do I represent it in code?

The data structure that represents a set of nodes connected by edges. Useful for modeling pairwise relationships, like social networks, web links or travel routes.

- Topic: Basics
- Type: data structure

## Example

Wrong:

```js
function dfs(graph, node) {
  for (const next of graph.get(node)) {
    dfs(graph, next);
  }
}
```

Right:

```js
function dfs(graph, node, visited = new Set()) {
  visited.add(node);
  for (const next of graph.get(node)) {
    if (!visited.has(next)) dfs(graph, next, visited);
  }
  return visited;
}
```

Without a `visited` set, any cycle makes the recursion run until the stack overflows.

## Common mistakes

- DFS on a cyclic graph that never ends because nothing tracks visited nodes.
- Adding an undirected edge in only one direction.

## Key points

- Traversals keep a `visited` set so cycles do not cause infinite loops.
- Sparse graphs use an adjacency list, such as a `Map` of arrays, not an n×n matrix.
- Undirected edges are added in both directions.

## Interview questions

### Adjacency list vs adjacency matrix: which should I use?

An adjacency list uses O(V + E) space and suits sparse graphs. A matrix uses O(V²) space but checks whether an edge exists in O(1).

### What is the time complexity of BFS and DFS on a graph?

Both are O(V + E) with an adjacency list, because each vertex and edge is processed once. With a matrix they are O(V²).

### Directed vs undirected graph: what is the difference?

In a directed graph each edge goes one way, like a link from page A to page B. In an undirected graph each edge works both ways, like a friendship.

## Related cards

- [Vertex](https://wonderium.dev/algorithms/vertex.md)
- [Edge](https://wonderium.dev/algorithms/edge.md)
- [Directed Graph](https://wonderium.dev/algorithms/directed-graph.md)
- [Breadth-First Search](https://wonderium.dev/algorithms/breadth-first-search.md)
- [Dijkstra's Algorithm](https://wonderium.dev/algorithms/dijkstra-algorithm.md)

---

- Level: [Algorithms](https://wonderium.dev/algorithms.md)
- HTML version: https://wonderium.dev/algorithms/graph
- Last updated: 2026-11-25
