I have a graph with n
nodes as an adjacency matrix.
Is it possible to detect a sink in less than O(n)
time?
If yes, how? If no
I have figured out a solution to this.
I'm assuming arrays are initialized with all 0's (otherwise N needs to be filled with 0) and that M is a adjacency matrix for the graph. I let n be the number of nodes (n = |V|).
j,i = 1;
N = new int[n]
while (j <= n && i <= n) {
if (N[i] == 1) {
i++
} else if (N[j] == 1) {
j++;
} else if (M[i,j] == 1) {
N[i] = 1
i++
} else if (i == j) {
j++
} else {
N[j] = 1
j++
}
}
for (z = 1 to n) {
if (N[z] == 0) {
return z
}
}
return NULL
Why this works (not formal proof): Any node with any edges going from it is not a universal sink. Thus, if M[i,j] is 1 for any j, i can not be a sink.
If M[i,j] is 0 for any i, then i does not have an edge to j, and j can not be a universal sink.
A 1 at N[i] designates that I know it isn't a sink, and any node that I know isn't a sink can be skipped on both i and j. I stop when either exeeds n.
This way I keep checking any nodes, that I still don't know isn't a sink, until 1 or 0 possible sinks remain.
Thus any node that is still 0 at the end of the loop must be the sink, and there will only be either 1 or 0 of those.
Why it is O(n): This always increments either i or j. It stops when either exeeds n. Thus the worst case for the loop is 2n. The work in the loop is constant. The last loop is worst case n. Hence the algorithm is O(3n) = O(n).
This solution is based on the idea of the celebrity problem, which is a way of considering the same problem.