~/coding-interview/graph-topological-sort-build-system-example.md

Graph Topological Sorting - Build System Order Example

2 min readNovember 20, 2020by Gorav Singal#coding-problems#graph#data-structure-for-interview
// TL;DR

Topological sort uses DFS with a stack — push a vertex after all its dependents are visited. The reversed stack gives you a valid build order. Only works on DAGs.

Graph Topological Sorting - Build System Order Example

Graph Topological Sorting

This is a well known problem in graph world. Topological sort is to put vertices in order and output a list of vertices in such an order that vertices are in order of dependencies. i.e. The vertices comes first is the independent one, then list the one which are dependent on those.

Connected Graph

In above Directed Graph, following can be possible topological sort order:

A B C D E F G H
OR
A C B E G D F H
OR
B E G A D C F H

Build System Example

The usage of this sort is in the Build system. A build system is where there are different projects or modules are to built. And, it is to decide which module to build first so that updated module can be integrated in the dependent project or module.

Code

class Node {
  //to represent a Vertex
  public String name;
  public List<Node> connectedNodes;
  //...some other data
  public List<Node> adj() {
    return this.connectedNodes;
  }
}
class Graph {
  private List<Node> nodes;
  public List<Node> nodes() {
    return this.nodes;
  }
  
}

public Stack<Node> topological(Graph g) {
  //assumming Graph has method nodes() which gives list of all nodes.
  List<Node> nodes = g.nodes();

  //Set to keep track of visited nodes
  Set<Node> visited = new HashSet();

  //For keeping nodes in order
  Stack<Node> stack = new Stack();

  for (Node node : nodes) {
    helper(node, visited, stack);
  }
}

private void helper(Node node, Set visited, Stack stack) {
    if (visited.contains(node)) {
      continue;
    }
    //mark node visited
    visited.add(node);

    //visit all attached nodes with this vertices
    //Assumming there is a method adj() which gives connected nodes to a vertex
    for (Node n : node.adj()) {
      //recursively visit each node's connected vertices
      helper(n, visited, stack);
    }

    //all connected vertices are exhausted. 
    //Lets add this to our order list
    stack.add(node);
}

//main 
Stack<Node> stack = topological(graph);
//print stack

Complexity

Its O(n)

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Min Priority Queue Implementation with Heap Data structure

Min Priority Queue Implementation with Heap Data structure

Min Priority Queue is a data structure which manage a list of keys(values). And…

Max Priority Queue Implementation with Heap Data structure

Max Priority Queue Implementation with Heap Data structure

Max Priority Queue is a data structure which manage a list of keys(values). And…

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…