Data Structures & AlgorithmsHardTCS CodeVita · Microsoft SDE OA
Eight vertices 0..7 receive the edges (0,1), (2,3), (4,5), (1,2), (5,6) in that order in a disjoint-set structure with union by size and path halving. What is the size of the largest connected component after all edges are added?
Eight vertices 0..7 receive the edges (0,1), (2,3), (4,5), (1,2), (5,6) in that order in a disjoint-set structure with union by size and path halving. What is the size of the largest connected component after all edges are added?
n=8; E=[(0,1),(2,3),(4,5),(1,2),(5,6)]
p=list(range(n)); sz=[1]*n
def f(x):
while p[x]!=x: p[x]=p[p[x]]; x=p[x]
return x
for a,b in E:
ra,rb=f(a),f(b)
if ra!=rb:
if sz[ra]<sz[rb]: ra,rb=rb,ra
p[rb]=ra; sz[ra]+=sz[rb]
print(max(sz[f(i)] for i in range(n)))What is printed?- A. 3
- B. 4
- C. 5
- D. 12
Correct answer: B. 4
Union by size tracks each root's component size, so the answer is the largest root size. Counting roots gives the number of components, counting edges is unrelated to component sizes, and an average over non-singleton components is a different quantity.
More Coding Interview Problems questions
- Compute the sum over all subarrays of the minimum element, for a = [3, 1, 2, 1, 3]. Subarrays are counted by position, so equal values in…
- Find the sum of the maximum of every window of length 3 in a = [1, 3, −1, −3, 5, 3, 6, 7] (windows slide one step at a time). python…
- In the reflected binary Gray code, the number with index i is i XOR (i >> 1). Using 0-based indices, what is the value printed for i = 5…
- How many binary strings of length 30 contain neither the substring "11" nor the substring "000"? python n=30 dp={('0',1):1,('1',1):1} for…
- How many primes p satisfy p ≤ 1,000,000 and p ≡ 3 (mod 4)? python N=106 s=bytearray([1])(N+1); s[0]=0; s[1]=0 for i in…
- The recursive extended Euclidean algorithm eg(a, b) returns (g, x, y) with a·x + b·y = g, using eg(a, b) = (g, y, x − (a//b)·y) when b ≠ 0…