Fun with Graphs
According to BoingBoing, Metawebis getting 15 million in funding. So of course they are hiring. The applicant is required to answer a few questions, one of which is:
I thought it sounded like fun:
Maybe if I find time to prove the space- & time-complexity, and finish the other questions I'll apply for an intership.
2. Imagine a graph that consists of directional links between nodes identified by small non-negative integers <> 2 succeeds, but inserting a second link 2 -> 1 would fail, since it would close the cycle 1 -> 2 -> 1.
In your favorite programming language, declare data structures to represent your graph, and give code for an "insert link" function that fails if a new link would close a cycle. What, roughly, is the space- and time-complexity of your solution?
I thought it sounded like fun:
class Node:
def __init__(self,name):
self._name = name
self._adjNodes = {}
def AddEdge(self,Node,EdgeVal):
if not Node.FindNode(self):
self._adjNodes[Node] = EdgeVal;
else:
print "Error: edge creates cycle. (%s to %s, weight: %s)" % (self._name, Node._name, EdgeVal)
def FindNode(self,Node):
for k,v in self._adjNodes.iteritems():
if k is Node or k.FindNode(Node):
return True
return False
# test it out.
n1 = Node("Node 1")
n2 = Node("Node 2")
n3 = Node("Node 3")
n4 = Node("Node 4")
n1.AddEdge(n4,10) # Legal
n2.AddEdge(n3,20) # Legal
n2.AddEdge(n1,30) # Legal
n4.AddEdge(n3,40) # Legal
n4.AddEdge(n2,50) # Illegal
n3.AddEdge(n1,60) # Illegal
n2.AddEdge(n4,70) # Legal
# another example
b1 = Node("b1")
b2 = Node("b2")
b1.AddEdge(b2,10)
b2.AddEdge(b1,234)
Maybe if I find time to prove the space- & time-complexity, and finish the other questions I'll apply for an intership.