⚡Flashcard Drill➔
NeetCode #162LC-1101MediumArrays & Hashing
← Back to All Problems

#162 · #1101 · The Earliest Moment When Everyone Become Friends(彼此熟识的最早时间)

📌 Problem Statement & Constraints

There are n people in a social network. Given logs where logs[i] = [timestamp, idA, idB] means the two people became friends at that time, return the earliest time at which all people are connected (or -1 if it never happens). Constraints: 1 <= n <= 1000, 1 <= logs.length <= 10^4; logs is not necessarily sorted.

💡 Core Algorithmic Approaches

  1. This is a connectivity problem: sort the logs by timestamp and union the pairs one by one.
  2. Use union-find and track the number of connected components. Each successful union decrements the count.
  3. The answer is the timestamp at which the component count first reaches 1.
  4. If n == 1 the answer is 0, since a single person is trivially all-connected.

💻 Benchmark Python3 Implementation

class Solution:
    def earliestAcq(self, logs: List[List[int]], n: int) -> int:
        if n == 1:
            return 0
        logs.sort(key=lambda x: x[0])      # chronological order
        parent = list(range(n))

        def find(x: int) -> int:
            while parent[x] != x:
                parent[x] = parent[parent[x]]   # path halving
                x = parent[x]
            return x

        groups = n
        for t, a, b in logs:
            ra, rb = find(a), find(b)
            if ra != rb:
                parent[ra] = rb
                groups -= 1
                if groups == 1:
                    return t
        return -1

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(m log m + m * alpha(n)) where m is the number of logs: sorting dominates, and the union-find operations are effectively constant.
💾 Space Complexity
O(n) for the parent array.

⚠️ Interview Pitfalls & Follow-ups

  • Processing the logs in input order: they are not sorted by timestamp, so the answer would be wrong.
  • Counting edges instead of components: the answer requires connectivity, not a spanning tree size.
  • Forgetting the n == 1 case: the loop would never set groups to 1 (it starts at 1), so it would fall through to -1. Handle it explicitly.
  • Recomputing connectivity from scratch after each log: O(m * n) instead of the near-linear union-find.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

彼此熟识的最早时间

在一个社交网络中,每个 id 为 0 到 n − 1 的人都代表一个人。给你一个日志数组 logs,其中 logs[i] = [timestampi, idi_a, idi_b] 表示 idi_a 和 idi_b 在 timestampi 时刻成为朋友。朋友关系是 相互 的,且具有 传递性 (朋友的朋友也是朋友)。请你返回所有人成为朋友的最早时间。如果无法使所有人都成为朋友,返回 −1。约束:2 ≤ n ≤ 1000;1 ≤ logs.length ≤ 10^4;logs[i].length == 3;0 ≤ timestampi, idi_a, idi_b ≤ 10^4;idi_a != idi_b。

核心要点

  • 并查集 + 按时间排序(标准解) :按 timestamp 升序遍历日志,每次尝试合并两个集合。
  • 用连通分量计数判终止 :初始有 n 个分量。每次成功合并使分量数减一;当分量数降为 1 时,当前时间即为答案。
  • 为什么必须先排序 :日志数组不一定按时间有序,而题目要求「最早时间」,因此必须按时间升序处理。
  • 并查集优化 :路径压缩(find 时把节点直接挂到根上)使均摊复杂度接近 O(α(n))。

常见陷阱

  • 不排序直接遍历 :日志可能乱序,会返回错误的时间。必须先按 timestamp 升序排序。
  • 忘记 n == 1 的边界 :只有一个人时,所有人(就他自己)从时间 0 起就是朋友,应返回 0,而不是走循环后返回 −1。
  • 用 BFS 每次重建图 :复杂度远高于并查集,且实现更复杂。
  • 忘记路径压缩 :在极端情况下(链状合并)find 会退化到 O(n),总复杂度上升到 O(m · n)。

参考实现

class Solution:
    def earliestAcq(self, logs: list[list[int]], n: int) -> int:
        parent = list(range(n))

        def find(x: int) -> int:
            while parent[x] != x:
                parent[x] = parent[parent[x]]     # 路径压缩
                x = parent[x]
            return x

        if n == 1:
            return 0                              # 只有一个人,已经「全部是朋友」

        cnt = n                                   # 连通分量数
        for t, a, b in sorted(logs):              # 必须按时间升序
            ra, rb = find(a), find(b)
            if ra != rb:
                parent[ra] = rb
                cnt -= 1
                if cnt == 1:
                    return t
        return -1