HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Vertex cover approximation in JavaScript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptcoverapproximationvertex

Problem

I believe this runs in \$O(V+E)\$ but I wouldn't be able to explain the reasons why. I was looking for some general code review and any help on understanding the runtime.

var Graph = function() {
    this.adj = {};
}

Graph.prototype.addEdge = function(v, w) {
    if (!Array.isArray(this.adj[v])) this.adj[v] = [];
    if (!Array.isArray(this.adj[w])) this.adj[w] = [];

    this.adj[v].push(w);
    this.adj[w].push(v);
}

var vertexCover = function(G) {
    var visited = {};
    var cover = [];

    var u;
    for (var v in G) {
        if (!visited[v]) {
            for (var i = 0; i < G[v].length; i++) {
                u = G[v][i];
                if (!visited[u]) {
                    visited[u] = true;
                    visited[v] = true;
                }
            }
        }
    }

    for (var x in visited) {
        cover.push(x);
    }
    return cover;
}

var ex = new Graph();
ex.addEdge(0, 1);
ex.addEdge(0, 2);
ex.addEdge(1, 3);
ex.addEdge(3, 4);
ex.addEdge(4, 5);
ex.addEdge(5, 6);
console.log('graph', ex.adj);

console.log(vertexCover(ex.adj));

Solution

As you can see after adding edges to the graph, G[v] has the list of neighbours of v, correct?
Therefore the length of G[v] for the vertex v is equal to the number of edges joining v.
Notice that each edge u-v appears twice in G, once in the neighborhood set of u, and once in the neighborhood of v (G[u] contains v and G[v] contains u both referring to the single edge u-v).
So these being said let's have a look at the code.

We iterate over all vertices in the outermost for loop;
for each vertex v in the set of vertices, we iterate over all edges connected to it.

Since each edge has appeared twice in the list (as mentioned above), we are basically counting (or visiting) each edge twice using these two nested loops.
Hence, the complexity of these two for loops could be O(E) where E is the number of edges in the graph.

Notice that the outer loop, iterates through all vertices any way. So, the complexity of the runtime cannot be less than O(V). This being said the complexity of the algorithm is the maximum of O(E) and O(V), which is exactly what O(V+E) means.

Context

StackExchange Code Review Q#113961, answer score: 2

Revisions (0)

No revisions yet.