Quoting from Dasgupta, Papadimitrou, and Vazirani textbook: “Trees A tree is an undirected graph that is connected and acyclic.” p.135 Trees have these properties, quoting from DPV again: A tree on n nodes has n − 1 edges Any connected, undirected graph G = (V, E) with |E| = |V| − 1 is a tree. […]

# Category: Algorithms

## Detect Cycle in a Directed Graph

A directed graph without any cycle is a Directed Acyclic Graph (DAG). If there is a cycle, then there will be a back edge, which goes backwards. For such edge(u,v), postorder number for u will be smaller than that of v, i.e. post(u) < post(v). So after DFS, if any edge satisfies post(u) < post(v) […]

## Connected Components in Graphs

There can be three types of graphs here. 1. Undirected Graph For undirected graphs, we can use Depth First Search (DFS) to find the connected component number for each vertex. The runtime is O(|V|+|E|). 2. Directed Graph Directed graphs can be of two types. Directed Acyclic Graphs (DAG) and General Directed Graphs. DAGs’s do not […]

## Topologically Sorting a DAG

In Directed Acyclic Graphs (DAG), there are no cycles. So it is simple to find the connected components just by sorting the vertices by post-order visit number in decreasing order after one run of DFS. The run time for DFS is again O(|V|+|E|)

## Finding x in an Infinite Array

This is a programming problem where the given array A is of infinite length and we have to find the position of a value x in it. The first n values are sorted and after n-th number, all remaining values in the array are None. For example: A= [1, 3, 5, 100, 102, 1050, 1061, […]