Sort the log items by their timestamp.
How can we model this problem as a graph problem?
Let's use a union-find data structure. At the beginning we have a graph with N nodes but no edges.
Then we loop through the events and unite each node until the number of connected components reach to 1. Notice that each time two different connected components are united the number of connected components decreases by 1.