Skip to content
BytePatterns

Smallest Equivalent String

MediumUnion-Find#union-find#strings~25m

Problem

Two strings a and b of equal length declare letter equivalences: a[i] is equivalent to b[i] for every i. Equivalence is reflexive, symmetric and transitive, so it groups the lowercase letters into classes. Given a third string text, replace each of its letters with the smallest letter of its class and return the alphabetically smallest string this produces.

Examples

Input:  a = "parker", b = "morris", text = "parser"
Output: "makkek"
Why:    the classes include {m, p}, {a, o}, {k, r, s} and {e, i}
Input:  a = "hello", b = "world", text = "hold"
Output: "hdld"
Why:    o shares a class with e and d, so it becomes d; h, l and d already lead theirs
Input:  a = "", b = "", text = "abc"
Output: "abc"
Why:    edge case, with no equivalences every letter stands alone

Hints

0 / 3

Stuck on the idea rather than the code? Path Compression covers it.