The problem asks to find the earliest time when everyone in a social group becomes acquainted with everyone else. Acquaintance is defined as being friends directly or indirectly (through a chain of friends). The input is an array of logs, where each log [timestamp, x, y]
indicates that person x
and person y
become friends at the given timestamp
.
The most efficient approach uses a combination of sorting and the Union-Find data structure.
1. Sorting:
The logs are first sorted in ascending order based on their timestamps. This ensures that we process friendships chronologically, allowing us to determine the earliest time everyone becomes acquainted.
2. Union-Find:
A Union-Find data structure is used to efficiently track connected components (groups of friends). Each person is initially in their own component. When two people become friends (a log entry is processed), their components are merged using the union
operation of the Union-Find.
find(x)
: This function determines the root of the component containing person x
. It uses path compression for optimization.union(x, y)
: This function merges the components containing x
and y
. It often employs a heuristic (like union by rank or union by size) to improve efficiency, reducing the tree height in the Union-Find structure.Algorithm:
logs
array by timestamp.UnionFind
data structure with n
elements, representing the n
people.[timestamp, x, y]
:
x
and y
are already in the same component using find(x)
and find(y)
.union(x, y)
.n
(the number of components) after each successful merge.n
becomes 1 (meaning everyone is in the same component), return the current timestamp
.n
becoming 1, it means everyone never became acquainted, so return -1.Time Complexity:
Space Complexity:
The provided code solutions in various languages demonstrate this algorithm efficiently. They implement the UnionFind
structure and apply the steps described above. Each solution's time and space complexity align with the analysis.