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?- A. 45 -1
- B. 50 -1
- C. 30 30
- 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
- Problem: Find a redundant edge that, when removed, leaves a tree (return the last such edge in input order). python def redundant(edges)…
- Problem: Return the alien-dictionary letter order from a sorted list of words (Kahn's algorithm, ties alphabetical). python import heapq…
- Problem: Count how many nodes are 'safe' (every path from them ends at a terminal node) in a directed graph. python def safe(g): color =…
- Problem: Find the minimum effort path in a grid where effort is the maximum absolute height difference between consecutive cells. python…
- Problem: Return the number of steps to reach the exit of a maze grid ('.' open, '+' wall) from an entrance, where an exit is an open…
- Problem: Count paths modulo 10⁹ + 7 from the top-left to the bottom-right of a 3 × 3 board whose centre is blocked, moving right, down or…