Dwarfs standing on the shoulders of giants


The aim of this puzzle is, given a list of couples mentor / person influenced, to compute the number of people involved in the longest succession of influences. This can be done by building a graph where an edge going from a vertex x to a vertex y represents the influence of person x on person y. Then the answer is the length of the longest path in the graph +1 (its diameter +1).

Difficulty: Medium · Skills: directed graph, longest path, DFS, depth propagation

What this puzzle tests in a coding interview

Dwarfs Standing on the Shoulders of Giants asks for the longest chain of influence in a directed acyclic graph. It checks whether you can model relations as a graph and compute depths without exploring the same chains repeatedly.

How to solve it, step by step

  1. Create a node for each person the first time their id appears.
  2. For each influence pair x then y, add y to the list of people influenced by x.
  3. Give every person a depth of 1, then when an edge is added, push depth plus one to the influenced person and recursively to everyone they influence if that depth increases.
  4. After all edges are read, the answer is the largest depth stored on any person.
  5. Print that maximum, which counts people in the longest chain.

Time and memory complexity

Depth propagation may revisit nodes when longer chains are discovered, so the worst case is above linear, but for the puzzle limits it runs fast; a memoised DFS from each root would be O(V + E).

Traps to avoid

Tip for a timed test

Explain the memoised version if asked: the length of the longest chain from a node is 1 plus the maximum over its children, and each node is computed once.

Python

Another example of nice OOP in Python. Instead of computing the diameter at the end, we keep updated for each vertex its depth, i.e its distance to its most ancient parent.

class Person(object):
    '''Represents a person, which has a unique id, a depth in the tree of relations
       and a list of persons she influenced'''
    def __init__(self, id):
        self.id, self.depth, self.influenced = id, 1, []

    def add(self, p):
        '''add person p amongst the person influenced'''
        self.influenced.append(p)

    def updateDepths(self):
        '''update depths of the persons influenced, according to self depth'''
        for p in self.influenced:
            if (p.depth < self.depth+1):
                p.depth = self.depth+1
                p.updateDepths()

# number of relations
N = int(input())
persons = {}
for i in range(N):
    x, y = [int(j) for j in input().split()]
    if not x in persons:
        persons[x] = Person(x)
    if not y in persons:
        persons[y] = Person(y)
    px, py = persons[x], persons[y]
    px.add(py)
    px.updateDepths()

maximum = 0
for p in persons.values():
    maximum = max(p.depth, maximum)

print(maximum)