Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: s1[i] and s2[i] are declared equivalent letters (the relation is reflexive, symmetric and transitive). Replace every letter of base by the smallest letter equivalent to it.
Problem: s1[i] and s2[i] are declared equivalent letters (the relation is reflexive, symmetric and transitive). Replace every letter of base by the smallest letter equivalent to it.
def smallest(s1, s2, base):
par = {c: c for c in "abcdefghijklmnopqrstuvwxyz"}
def find(x):
while par[x] != x: x = par[x]
return x
for a, b in zip(s1, s2):
ra, rb = find(a), find(b)
if ra != rb:
par[max(ra, rb)] = min(ra, rb)
return "".join(find(c) for c in base)
print(smallest("abc", "cde", "eed"))What is printed?- A. aab
- B. ccd
- C. aad
- D. eeb
Correct answer: A. aab
The pairs a~c, b~d, c~e give groups {a, c, e} and {b, d}. Union by smaller root keeps the minimum as representative, so e → a and d → b: 'aab'. Mapping only through direct pairs (e → c) gives 'ccd'.
More Coding Interview Problems questions
- Problem: Find all roots that give a tree of minimum height, by repeatedly peeling off leaves. python def mht(n, edges): adj = [set() for…
- Problem: Build a Huffman code for symbol frequencies and report the total number of bits for the encoded message (Σ freq × code length)…
- Problem: Balloons span horizontal intervals [start, end]; an arrow shot at x bursts every balloon with start ≤ x ≤ end. Find the minimum…
- Problem: A knight walks from the top-left to the bottom-right cell moving only right or down; each cell adds its value to his health…
- Problem: Can s3 be formed by interleaving s1 and s2 (keeping each string's own order)? python def inter(s1, s2, s3): if len(s1) + len(s2)…
- Problem: Count palindromic substrings (by position, so equal strings at different places count separately) by expanding around every…