# An Online Algorithm to Check for Bipartite Graphs

### Bipartite Graphs

A graph $$G(V, E)$$ is called bipartite if its vertices can be divided into two groups $$X$$ and $$Y$$ such that every edge connects one vertex from $$X$$ and one vertex from $$Y$$. The graph drawn below is bipartite.

Given a graph, can you determine if it is bipartite?

This problem is pretty straightforward because the vertices of a bipartite graph can be colored with two colors such that every edge connects two vertices of different colors (see above). This property is called 2-colorability. The converse is also true, that is if a graph is 2-colorable, it is also bipartite. Hence, it order to check for bipartiteness, we can run a Breadth First Search on the graph and color the vertices as we discover them. It would take $$O(V+E)$$ time and storage.

### An Online Variant

First of all, what is an online algorithm? An online algorithm is an algorithm that processes the input in a piece by piece in a sequential manner and have access to limited storage. These algorithms are useful in many realistic scenarios.

Now consider an online variant of the previous problem: suppose your algorithm gets a single pass over the edges of a graph and has access to only $$O(V)$$ storage. In other words, the edges are fed into the algorithm one at a time, but the algorithm cannot store all of them. Can you determine if this graph is bipartite?

This is a practical problem because a graph with $$|V|$$ vertices can have as many as $$|V|^2$$ edges. For instance, if a graph has $$10^{10}$$ vertices, there can be $$O(10^{20})$$ edges. Storing them in the memory might be impossible. The problem above attempts to bypass this issue by getting the edges sequentially, and never storing all of them. I’ll show that it is indeed possible to design such an algorithm with only $$O(E\log V)$$ runtime.

We’ll use the 2-colorability property once more. In the beginning, the graph is 2-colorable since all the vertices are disjoint. Let’s color all the vertices to be red. Every time a new edge is added to the graph, it connects two vertices of either different or same colors. In the former case, the graph remains bipartite. In the later case, one of the following two scenarios may occur:

1. The edge connects two vertices from the same connecting component. Now, if the edge connects two vertices of same color, the graph is no longer 2-colorable. We can output FAIL and stop.
2. The edge connects two vertices from different connected components. In this case, if the edge connects two edges of the same color, the graph is still 2-colorable. However, we need to flip colors of all the vertices in one of the connected components (see below).

A naive way to do #2 would be to flip color of every vertex in one of the connected components. This may take $$O(V)$$ time for each edge, the total runtime being $$O(EV)$$. We need a smarter way.

One potential approach is to do the flipping in a lazy manner: if #2 happens, only remember that colors in a connected components need to be flipped, instead of actually flipping them. When the algorithm checks the color of a vertex,

• go through your records to find the connected components the vertex was previously in.
• Observe how many of those connected components had their colors flipped.
• Since all vertices started as red, the number of flips determine current color of that vertex.

This reminds us of a data structure called Union-Find.

### A Quick Intro to Union-Find

This data structure is is essentially a list of mutually disjoint sets. It has three methods:

• make-set: makes a set with a unique id
• find(x): given element $$x$$, finds the id of the set $$x$$ belongs to.
• union(x, y): performs the set-union on the sets $$x$$ and $$y$$ belong to.

Union-Find is usually implemented as a forest of trees, with root of every tree being its id. Every node contains a pointer to its parent. Roots contain pointers to themselves. find(x) looks for the root of a tree. union(x, y) first does find(x) and find(y), then attaches the root of y as a child to the root of x.

In a naive implementation, the cost of the find and union functions are $$O(n)$$. However, those can be reduced to $$O(\log n)$$ via a technique called union by rank. In this technique, a shorter tree is always attached to a taller tree. You can easily show (by induction) that such a tree with height $$n$$ must contain atleast $$2^n$$ nodes. In other words, the time complexity for this data structure is $$O(\log n)$$.

### Faster Algorithm Using Union Find

In our problem, every connected component can be thought of as a disjoint set. Every node starts in its own set. When two connected components are merged, we perform set-union over their corresponding sets. Now, notice that, the root of every tree can remember if the connected component needs to flip color during the union. When we call find on an element, we’ll pass through all its ancestors, which were roots in some previous connected components. We can check each of them to see if those components had their colors flipped. Since each find costs $$O(\log V)$$ time, computing the color of each node requires $$O(\log V)$$ time, too. Now, each of the steps #1 and #2 in the previous algorithm takes $$O(\log V)$$ time. Hence, the total runtime for our modified algorithm is $$O(E\log V)$$.

### Appendix

In Union Find, there is another technique, called Path Compression, which (along with Union by Rank) reduces the data structure’s  amortized complexity to $$O(\alpha(n))$$. The previous algorithm works with path compression, but needs to be modified. This is left as an exercise to the reader.

# Generating All Subsets of Size k in Python

Suppose you are given a set $$S$$ with $$n$$ elements and you need to generate every subset of size $$k$$ from it. For instance, if $$S=\{3,4,5\}$$ and $$k=2$$, then the answer would be $$\{3,4\}$$, $$\{3,5\}$$, $$\{4,5\}$$. So, how would you do that in Python?

First of all, this is a really simple exercise. Stuff like this often comes up when someone writes a moderately large script. I wanna talk about this one in particular because it has a combinatorial solution.

Before I show it to you, I highly recommend you think about it on your own.

#### Solution

Notice that if you convert the set to a list, every element is assigned to a unique index between $$0$$ and $$n-1$$. So, it suffices to generate all the subsets of size $$k$$ from $$\{0,1,\ldots,n-1\}$$.

Now, every such subset falls into one of two categories: either it contains $$n-1$$ or it doesn’t.

If $$n-1$$ belongs to the subset, the rest of its elements form a subset of size $$(k-1)$$ in $$\{0,1,\ldots,n-2\}$$.

If $$n-1$$ doesn’t belong to the subset, then that subset is also a subset of $$\{0,1,\ldots,n-2\}$$.

This is essentially a recursion. So, we are done.

Pretty neat, eh?

def gen_subset(n, k):
if n >= 0 and n >= k >= 0:
if n == 0 or k == 0:
yield set()
elif n == k:
# returns {0, 1, ..., n-1}
yield set(range(n))
else:
# ksubsets without n-1
yield from gen_subset(n-1, k)
# ksubsets with n-1
for subset in gen_subset(n-1, k-1):
subset.add(n-1)
yield subset
else:
raise ValueError("Illegal Parameters")


# Lie Detectors and the Story of Halting Turing Machines

Is it possible to design a machine that detects lies? Sure, people have already built devices called polygraphs that monitor blood pressure, respiration, pulse etc. to determine if a person is giving false information. However, that is not same as “detecting lies” because polygraphs merely measure physical effects of telling lies. On the top of that, they are hella inaccurate. I am talking about REAL lie detectors, ie. machines that can instantly validate the statements themselves. Can we actually make such machines? (*insert new startup idea*)

Well, turns out if we ever could make such machines, they would become incredibly handy tools for scientists and mathematicians. That’s because they could babble all sorts of scientific and mathematical conjectures to such a machine, if it beeped, they would know those conjectures were false. Their conversation might go like this:

Crazy Physicist: Higgs Boson exists.
Machine: *Says Nothing*
Crazy Physicist: Ureka! I was right all along.

Computer Scientist: P=NP #changemymind
Machine: *beep*
Computer Scientist: OMG. P=/=NP. I just became a millionaire.

Clearly, you can see how these lie detectors would trivialize almost every known problem of science and mathematics. Then, a very legit question would be why nobody even tried to build such a machine. Indeed, humankind has spared far more effort after making junks like philosopher stones and elixir of life.

Turns out there is something fundamentally wrong about the design of the lie detectors. Before I get to the details, let me tell you a cool life hack. If you ever meet people that claim to be oracles, do this to them:

You: Will I offer you $10? Whatever the oracle says, do the opposite. This clearly shows the oracles cannot predict the future. The same thing is true for our lie detectors. Here is why: Suppose you brought your friend Joe to show him the lie detector you bought. Now do the following: You: I’m gonna hand Joe$10.

Whatever the lie detector says, do the opposite.

Therefore, just as above, our precious lie detectors cannot exist. However, they did have a purpose. They helped me to show you a proof technique called Cantor’s Diagonal Argument. It is a really nifty tool to prove many advanced statements in computability theory. Here is the general idea:

• First you assume a machine with utterly unbelievable functions exists.
• Then you come up for a statement or input for this machine using its own functions.
• Finally, show that existence of such an input is contradictory to the existence of the machine itself.

As I’m running out of time, I’ll give you just one example of this technique. First proven by Alan Turing, it’s still one of the most famous proofs in computability theory.

Halting Turing Machine (HTM) is a special type of Turing machine that can instantly determine whether another Turing Machine halts on a specific input. In English, this means HTM is a cool app that can tell you whether one of the apps in your smartphone is gonna become unresponsive forever for a specific environment condition inside your smartphone. HTM would be a handy app, right? If HTM tells you an app is gonna be unresponsive beforehand, you’ll save time by not installing that crappy app. However, like all good things in computability theory, turns out HTM cannot exist either. This is because what if an evil developer created an app like this?

• Give my app’s code and current environment condition of the smartphone to the HTM
• Whatever the HTM says about my app, do the opposite inside the app.

Hence HTM is unable to predict what this evil dev’s app will do, and that’s why HTM cannot exist.

That’s it for today. I hope you enjoyed this blogpost. If you want to learn Computability Theory for real, I highly recommend Michael Sipser’s book.