FMTechnical notes
Portfolio
Back to the blog

Computer Science · Intermediate · Manual

Graphs: relationships, paths, and networks

A graph models relationships between entities. In insurance systems, it can represent how policies connect to claims, customers, and coverages.

After reading this
  • Represent a graph using adjacency lists
  • Implement BFS to find the shortest path in number of steps
  • Implement DFS to detect cycles or validate connections
  • Choose between BFS and DFS according to the specific problem
01 / 06

Graph structure

A graph is a collection of nodes (vertices) connected by edges. In an insurance system, each node could be an entity such as customer, policy, claim, or coverage. Edges represent real relationships: a customer has a policy, a policy covers a claim.

To store this structure in memory, we use an adjacency list. That is, an object where each key is a node and its value is a list of neighboring nodes.

ts
type Graph = Record<string, string[]>;

const insuranceGraph: Graph = {
  'customer-A': ['policy-001'],
  'policy-001': ['claim-X', 'coverage-Y'],
  'claim-X': ['customer-A'],
  'coverage-Y': []
};
02 / 06

Breadth-First Search (BFS)

BFS explores a graph level by level from a starting node. It's ideal when you need to find the shortest path in terms of number of steps (not weight). For example, how many degrees of separation exist between two insured entities.

It uses a queue to maintain pending nodes. Each time you visit a new node, you record the distance from the start.

ts
interface Queue<T> {
  enqueue(item: T): void;
  dequeue(): T | undefined;
  isEmpty(): boolean;
}

class SimpleQueue<T> implements Queue<T> {
  private items: T[] = [];
  
  enqueue(item: T) { this.items.push(item); }
  dequeue() { return this.items.shift(); }
  isEmpty() { return this.items.length === 0; }
}

function bfs(graph: Graph, start: string, target: string): number | null {
  const visited = new Set<string>();
  const queue = new SimpleQueue<[string, number]>(); // [node, distance]
  
  queue.enqueue([start, 0]);
  visited.add(start);
  
  while (!queue.isEmpty()) {
    const [current, distance] = queue.dequeue()!;
    
    if (current === target) return distance;
    
    for (const neighbor of graph[current] || []) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.enqueue([neighbor, distance + 1]);
      }
    }
  }
  
  return null; // Not found
}
03 / 06

Depth-First Search (DFS)

DFS explores a path as deep as possible before backtracking. It's useful for verifying if there's any path between two nodes or detecting cycles. For example, validating if a customer is indirectly related to a suspicious claim.

It can be implemented recursively or with an explicit stack. For cycle detection, we keep track of the current path.

ts
function dfs(
  graph: Graph, 
  start: string, 
  target: string, 
  visited: Set<string> = new Set(),
  path: string[] = []
): boolean {
  if (start === target) return true;
  
  visited.add(start);
  path.push(start);
  
  for (const neighbor of graph[start] || []) {
    if (!visited.has(neighbor)) {
      if (dfs(graph, neighbor, target, visited, path)) {
        return true;
      }
    }
  }
  
  path.pop();
  return false;
}

function hasCycle(graph: Graph, node: string, visited: Set<string>, recStack: Set<string>): boolean {
  visited.add(node);
  recStack.add(node);

  for (const neighbor of graph[node] || []) {
    if (!visited.has(neighbor)) {
      if (hasCycle(graph, neighbor, visited, recStack)) return true;
    } else if (recStack.has(neighbor)) {
      return true; // Cycle detected
    }
  }

  recStack.delete(node);
  return false;
}
04 / 06

When to use BFS vs DFS

BFS guarantees the shortest path in steps but requires memory proportional to the width of the widest level. DFS uses less memory (maximum depth) but doesn't guarantee the shortest path.

In insurance systems, use BFS when you need to calculate the minimum number of hops between entities (e.g., for proximity fraud analysis). Use DFS when you only need to verify if any suspicious connection exists.

05 / 06

Implementation considerations

Not all data structures are suitable for large graphs. An adjacency list is space-efficient compared to a matrix. Moreover, you often don't need a full graph library — basic BFS and DFS solve most real-world problems.

Avoid unnecessary abstractions until you have a clear performance or complexity case. Writing BFS or DFS in fifteen clear lines is better than depending on a heavy library without truly understanding what it does.

06 / 06

Real-world application in insurance

Imagine a system where you must determine if a customer is connected to a fraudulent claim. BFS will give you the least number of steps possible between them, while DFS will simply tell you if they are connected.

Additionally, you can use DFS to detect cycles in cross-claims that could indicate coordinated fraud attempts.

Graph traversal● interactive
A1B2C3D4E5
Practice

Detect fraudulent connections

Given a graph of customers, policies, and claims, use DFS to verify if a customer is connected to a claim marked as fraudulent. Also implement BFS to find the minimum distance between them.

Show a hint

Start by building the graph as an object with adjacency lists. Then implement separate functions for BFS and DFS following the previous examples.