New task added. The algorithm can be changed to O(n) if we build graph
and use BFS.