Graph

Term side of the Card.
Topic: Basics
Unit title: Graph
Categories: Data structure
Explanation side of the Card

Explanation: 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.

Example

Wrongjs
function dfs(graph, node) {
  for (const next of graph.get(node)) {
    dfs(graph, next);
  }
}
Rightjs
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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy