Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the earliest time when all employees are connected, given friendship logs (time, a, b) and n people.

Problem: Find the earliest time when all employees are connected, given friendship logs (time, a, b) and n people.
def earliest(logs, n):
    p = list(range(n)); comps = n
    def f(x):
        while p[x] != x: p[x] = p[p[x]]; x = p[x]
        return x
    for t, a, b in sorted(logs):
        ra, rb = f(a), f(b)
        if ra != rb:
            p[ra] = rb; comps -= 1
            if comps == 1: return t
    return -1
logs = [(20, 0, 1), (3, 3, 4), (45, 1, 5), (6, 2, 3), (9, 1, 2), (30, 4, 5), (50, 0, 5)]
print(earliest(logs, 6), earliest(logs[:3], 6))
What is printed?
  1. A. 45 -1
  2. B. 50 -1
  3. C. 30 30
  4. D. 30 -1

Correct answer: D. 30 -1

Process logs in time order with union-find and stop when one component remains. Time 3: {3,4}; 6: {2,3,4}; 9: {1,2,3,4}; 20: adds 0; 30: 4–5 joins 5 → all six connected. The first three logs alone never connect everyone. O(m log m) for sorting.

More Coding Interview Problems questions

Exams that ask this topic