1. Home
  2. Explore
  3. Computer Science
  4. Graph Algorithms Interview Course

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Graph Algorithms Interview Course

Graph Algorithms for Technical Interviews

Introduction

This course covers the core graph patterns needed for technical interviews. By mastering a handful of algorithms, you can solve approximately 80% of graph problems encountered in coding interviews. The key is to visualize graphs as pictures and to understand the underlying patterns.

Prerequisites: Basic programming knowledge, some familiarity with recursion. No prior graph knowledge is assumed.


Graph Basics

Definition of a Graph

A graph is a collection of nodes (also called vertices) and edges (connections between nodes).

  • Nodes are typically visualized as circles containing data (e.g., letters, numbers).

  • Edges are the lines connecting nodes. They represent relationships.

A graph is a way of describing relationships between "things" (nodes) using connections (edges). For example, cities connected by roads, or courses linked by prerequisites.

Directed vs. Undirected Graphs

  • Directed graph: Edges have arrowheads showing direction. Travel is only allowed in the direction of the arrow. Example: node A can go to B, but B cannot return to A unless there is a reverse edge.

  • Undirected graph: Edges have no arrowheads. Travel is allowed in both directions. Acts like a two-way street.

A neighbor of a node is any node reachable via a single edge, obeying the direction of the edge.

Adjacency List Representation

An adjacency list is the most common programmatic representation of a graph. It is typically a hash map (object, dictionary, unordered map) where:

  • Each key is a node.

  • The corresponding value is an array (or list) of that node's neighbors (outgoing edges).

Example (directed graph):

const graph = {
  a: ['b', 'c'],
  b: ['d'],
  c: ['e'],
  d: ['f'],
  e: [],
  f: []
};
  • Even a node with no neighbors (like e) must appear as a key with an empty array.

  • The adjacency list allows constant-time lookup of a node's neighbors.

When sketching algorithms, use the visual graph (circles and arrows). In code, use adjacency lists.


Graph Traversal

Depth-First Traversal (DFS)

Concept: Explore as far as possible along one direction before backtracking. In a graph, this means picking a neighbor and diving deep until you hit a dead end, then returning to try another neighbor.

Data Structure: DFS uses a stack (Last-In-First-Out). This can be an explicit array (using push/pop) or the implicit call stack via recursion.

Algorithm (iterative using explicit stack):

  1. Initialize a stack with the starting node.

  2. While the stack is not empty:

    • Pop the top node (current).

    • Process current (e.g., print it).

    • For each neighbor of current (from the adjacency list), push the neighbor onto the stack.

  3. Continue until the stack is empty.

Implementation in JavaScript (iterative DFS):

const depthFirstPrint = (graph, source) => {
  const stack = [source];
  while (stack.length > 0) {
    const current = stack.pop();
    console.log(current);
    for (let neighbor of graph[current]) {
      stack.push(neighbor);
    }
  }
};

Recursive DFS:

const depthFirstPrint = (graph, source) => {
  console.log(source);
  for (let neighbor of graph[source]) {
    depthFirstPrint(graph, neighbor);
  }
};
  • The recursive version uses the call stack implicitly.

  • No explicit base case is needed because when a node has no neighbors, the loop runs zero times, which acts as the base case.

Important: The order of DFS depends on the order neighbors are pushed. Any depth-first order is valid.

Breadth-First Traversal (BFS)

Concept: Explore all neighbors at the current depth before moving deeper. This explores nodes in layers outward from the start.

Data Structure: BFS uses a queue (First-In-First-Out). Use array with shift (remove front) and push (add to back).

Algorithm (iterative only):

  1. Initialize a queue with the starting node.

  2. While the queue is not empty:

    • Shift the front node (current).

    • Process current.

    • For each neighbor of current, push the neighbor to the back of the queue.

  3. Continue until the queue is empty.

Implementation in JavaScript (BFS):

const breadthFirstPrint = (graph, source) => {
  const queue = [source];
  while (queue.length > 0) {
    const current = queue.shift();
    console.log(current);
    for (let neighbor of graph[current]) {
      queue.push(neighbor);
    }
  }
};

Comparison: DFS and BFS explore the same nodes but in different orders. DFS uses a stack; BFS uses a queue. The code structure is nearly identical; only the operations on the container differ (pop vs. shift).


Has Path Problem (Directed, Acyclic Graph)

Problem: Given a directed acyclic graph (no cycles), a source node, and a destination node, return true if there exists a path from source to destination, otherwise false.

Approach: Either DFS or BFS works. In the approach video, DFS is traced. Because the graph is acyclic, no visited set is needed (no infinite loops). However, in general, for cyclic graphs, visited sets are required.

DFS Recursive Solution (JavaScript):

const hasPath = (graph, src, dst) => {
  if (src === dst) return true;
  for (let neighbor of graph[src]) {
    if (hasPath(graph, neighbor, dst) === true) {
      return true;
    }
  }
  return false;
};

BFS Iterative Solution (JavaScript):

const hasPath = (graph, src, dst) => {
  const queue = [src];
  while (queue.length > 0) {
    const current = queue.shift();
    if (current === dst) return true;
    for (let neighbor of graph[current]) {
      queue.push(neighbor);
    }
  }
  return false;
};

Complexity:

  • Let nnn = number of nodes, eee = number of edges.

  • Time: O(e)O(e)O(e) — each edge is traversed at most once.

  • Space: O(n)O(n)O(n) — stack/queue can hold up to nnn nodes.

  • Alternatively, define nnn as nodes only: worst-case edges ≈n2\approx n^2≈n2, so time O(n2)O(n^2)O(n2) and space O(n)O(n)O(n).


Undirected Path Problem (With Cycles)

Problem: Given an undirected graph as an edge list, two nodes, return whether a path exists between them. The graph may contain cycles, so a visited set is essential.

Steps:

  1. Convert edge list to adjacency list (undirected, so add both directions).

  2. Traverse using DFS or BFS with a visited set to avoid cycles.

Edge List to Adjacency List (JavaScript):

const buildGraph = (edges) => {
  const graph = {};
  for (let edge of edges) {
    const [a, b] = edge;
    if (!(a in graph)) graph[a] = [];
    if (!(b in graph)) graph[b] = [];
    graph[a].push(b);
    graph[b].push(a);
  }
  return graph;
};

DFS Recursive with Visited Set (JavaScript):

const hasPath = (graph, src, dst, visited) => {
  if (src === dst) return true;
  if (visited.has(src)) return false;
  visited.add(src);
  for (let neighbor of graph[src]) {
    if (hasPath(graph, neighbor, dst, visited) === true) {
      return true;
    }
  }
  return false;
};

const undirectedPath = (edges, nodeA, nodeB) => {
  const graph = buildGraph(edges);
  const visited = new Set();
  return hasPath(graph, nodeA, nodeB, visited);
};
  • The visited set prevents infinite recursion when cycles exist.

  • Each node is processed once.

Complexity: O(e)O(e)O(e) time, O(n)O(n)O(n) space (for visited set and recursion stack).


Connected Components Count

Problem: Given an undirected graph (adjacency list), count the number of connected components.

Approach:

  1. Initialize a visited set.

  2. Loop through every node of the graph.

  3. For each node not yet visited, start a traversal (DFS or BFS) that explores its entire component, marking nodes as visited.

  4. Increment a counter each time a new traversal begins.

Implementation (JavaScript):

const explore = (graph, current, visited) => {
  if (visited.has(String(current))) return false;
  visited.add(String(current));
  for (let neighbor of graph[current]) {
    explore(graph, neighbor, visited);
  }
  return true; // explored a new component
};

const connectedComponentsCount = (graph) => {
  const visited = new Set();
  let count = 0;
  for (let node in graph) {
    if (explore(graph, node, visited) === true) {
      count += 1;
    }
  }
  return count;
};

Note: In JavaScript, object keys are strings, but values in arrays may be numbers. Convert nodes to strings when using a Set to ensure type consistency.

Complexity: O(e)O(e)O(e) time, O(n)O(n)O(n) space.


Largest Component

Problem: Given an undirected graph, return the size (number of nodes) of the largest connected component.

Approach:

  1. Iterate over all nodes.

  2. For each unvisited node, perform a DFS that returns the size of its component.

  3. Track the maximum size encountered.

Helper function: exploreSize returns the size of the component, using recursion and a visited set.

Implementation (JavaScript):

const exploreSize = (graph, node, visited) => {
  if (visited.has(String(node))) return 0;
  visited.add(String(node));
  let size = 1; // count current node
  for (let neighbor of graph[node]) {
    size += exploreSize(graph, neighbor, visited);
  }
  return size;
};

const largestComponent = (graph) => {
  const visited = new Set();
  let longest = 0;
  for (let node in graph) {
    const size = exploreSize(graph, node, visited);
    if (size > longest) longest = size;
  }
  return longest;
};

Complexity: O(e)O(e)O(e) time, O(n)O(n)O(n) space.


Shortest Path

Problem: Given an undirected graph (edge list) and two nodes, find the length of the shortest path (number of edges) between them. If no path exists, return -1.

Approach: Use BFS because it explores nodes in order of increasing distance from the start. The first time the destination is reached, the distance is minimal.

  • Store pairs (node, distance) in the queue.

  • Use a visited set to avoid revisiting nodes.

Implementation (JavaScript):

const buildGraph = (edges) => {
  const graph = {};
  for (let [a, b] of edges) {
    if (!(a in graph)) graph[a] = [];
    if (!(b in graph)) graph[b] = [];
    graph[a].push(b);
    graph[b].push(a);
  }
  return graph;
};

const shortestPath = (edges, src, dst) => {
  const graph = buildGraph(edges);
  const visited = new Set([src]);
  const queue = [[src, 0]]; // [node, distance]
  while (queue.length > 0) {
    const [node, distance] = queue.shift();
    if (node === dst) return distance;
    for (let neighbor of graph[node]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push([neighbor, distance + 1]);
      }
    }
  }
  return -1;
};
  • Distance is incremented when adding neighbors to the queue.

  • Mark nodes as visited when they are added to the queue (not when removed) to avoid duplicate entries.

Complexity: O(e)O(e)O(e) time, O(n)O(n)O(n) space.


Grid Graphs

Grid graphs treat positions on a 2D grid as nodes. Edges exist between horizontally or vertically adjacent cells (up, down, left, right). This allows graph algorithms to be applied to grid problems like counting islands.

Island Count

Problem: Given a 2D grid of 'L' (land) and 'W' (water), count the number of islands. An island is a vertically or horizontally connected region of land.

Approach:

  1. Iterate over every cell (r, c).

  2. If the cell is land and has not been visited, start a DFS that marks all contiguous land cells as visited.

  3. Increment island count for each such DFS.

Neighbor formula:

  • Up: (r-1, c)

  • Down: (r+1, c)

  • Left: (r, c-1)

  • Right: (r, c+1)

Base cases:

  • Out of bounds: stop.

  • Water cell: stop.

  • Already visited: stop.

Implementation (JavaScript):

const islandCount = (grid) => {
  const visited = new Set();
  let count = 0;
  for (let r = 0; r < grid.length; r++) {
    for (let c = 0; c < grid[0].length; c++) {
      if (explore(grid, r, c, visited) === true) {
        count += 1;
      }
    }
  }
  return count;
};

const explore = (grid, r, c, visited) => {
  const rowInbounds = 0 <= r && r < grid.length;
  const colInbounds = 0 <= c && c < grid[0].length;
  if (!rowInbounds || !colInbounds) return false;
  if (grid[r][c] === 'W') return false;
  
  const pos = r + ',' + c; // string key for visited set
  if (visited.has(pos)) return false;
  visited.add(pos);
  
  explore(grid, r - 1, c, visited);
  explore(grid, r + 1, c, visited);
  explore(grid, r, c - 1, visited);
  explore(grid, r, c + 1, visited);
  
  return true; // explored a new island
};
  • The visited set stores strings like "0,1" to avoid collisions (e.g., (12,4) vs (1,24)).

  • The explore function returns true only when it starts on an unvisited land cell, indicating a new island.

Complexity: Let RRR = number of rows, CCC = columns. Time: O(R×C)O(R \times C)O(R×C) — every cell processed at most once. Space: O(R×C)O(R \times C)O(R×C) for the visited set.

Minimum Island

Problem: Given the same grid, find the size of the smallest island. Return the minimum number of land cells in any connected region.

Approach: Similar to island count, but instead of counting islands, compute the size of each island and track the minimum.

Implementation (JavaScript):

const minimumIsland = (grid) => {
  const visited = new Set();
  let minSize = Infinity;
  for (let r = 0; r < grid.length; r++) {
    for (let c = 0; c < grid[0].length; c++) {
      const size = exploreSize(grid, r, c, visited);
      if (size > 0 && size < minSize) {
        minSize = size;
      }
    }
  }
  return minSize;
};

const exploreSize = (grid, r, c, visited) => {
  const rowInbounds = 0 <= r && r < grid.length;
  const colInbounds = 0 <= c && c < grid[0].length;
  if (!rowInbounds || !colInbounds) return 0;
  if (grid[r][c] === 'W') return 0;
  
  const pos = r + ',' + c;
  if (visited.has(pos)) return 0;
  visited.add(pos);
  
  let size = 1; // count current cell
  size += exploreSize(grid, r - 1, c, visited);
  size += exploreSize(grid, r + 1, c, visited);
  size += exploreSize(grid, r, c - 1, visited);
  size += exploreSize(grid, r, c + 1, visited);
  
  return size;
};
  • The exploreSize function returns the total number of land cells in the island, avoiding double-counting via the visited set.

  • Only non-zero sizes (actual islands) are considered for the minimum.

Complexity: Same as island count: O(R×C)O(R \times C)O(R×C) time and space.


Key Patterns Summary

  1. Traversal alternatives: DFS (stack/recursion) or BFS (queue).

  2. Cycle prevention: Use a visited set (typically a Set for O(1)O(1)O(1) lookup).

  3. Convert edge list to adjacency list for easier traversal.

  4. Connected components: Iterate over all nodes; start a traversal for each unvisited node; count or measure size.

  5. Shortest path: BFS with distance tracking in the queue.

  6. Grid graphs: Treat each cell as a node; neighbors are up/down/left/right; always check bounds before indexing.

Mastering these patterns provides a toolkit to solve the majority of graph problems encountered in technical interviews.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent