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?
  1. A. aab
  2. B. ccd
  3. C. aad
  4. 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

Exams that ask this topic