Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: n servers are joined by cables one at a time. Count the connected groups at the end and how many cables were redundant (joined two servers that were already connected).
Problem: n servers are joined by cables one at a time. Count the connected groups at the end and how many cables were redundant (joined two servers that were already connected).
def run(n, edges):
par = list(range(n))
def find(x):
while par[x] != x:
par[x] = par[par[x]]
x = par[x]
return x
comps, red = n, 0
for u, v in edges:
ru, rv = find(u), find(v)
if ru == rv:
red += 1
else:
par[ru] = rv; comps -= 1
return comps, red
c, r = run(8, [(0,1),(2,3),(1,3),(4,5),(6,6),(5,7),(0,2)])
print(c, r)What is printed?- A. 3 2
- B. 3 1
- C. 4 2
- D. 2 2
Correct answer: A. 3 2
Groups end as {0,1,2,3}, {4,5,7} and {6}: 3 components. Two cables are redundant: the self-loop (6,6) and (0,2), which arrives after 0 and 2 are already linked through 1–3. Forgetting that a self-loop is redundant gives 1.
More Coding Interview Problems questions
- Problem: Task IDs 0..5 with dependencies u → v (u before v). The scheduler always runs the SMALLEST available ID next. python import heapq…
- Problem: Dijkstra with a lazy binary heap: outdated heap entries are skipped when popped. Report the distance to node 4 and how many stale…
- Problem: Longest increasing subsequence in O(n log n) with a 'tails' array (tails[i] = smallest possible tail of an increasing subsequence…
- Problem: Return the length of the shortest string that contains both a and b as subsequences. python def scs(a, b): m, n = len(a), len(b)…
- Problem: The reflected binary Gray code of i is i ^ (i >> 1). At which position of the 3-bit Gray sequence does the code 6 (110) appear?…
- Problem: A permissions engine isolates bits of a mask. python x = 88 print(x & -x, x & (x - 1)) What is printed?