770. Smallest Equivalent Word
A translator is aligning two alphabets. The strings a and b have the same length, and for every index i the letters a[i] and b[i] are declared interchangeable. Interchangeability behaves like equality: it is symmetric (if x can replace y then y can replace x) and transitive (if x can replace y and y can replace z, then x can replace z). A letter that appears in no pair can only replace itself, and every letter can replace itself.
Rewrite the string base by replacing each of its letters with the alphabetically smallest letter that is interchangeable with it. Return the rewritten string, which has the same length as base.
Example 1
- Input:
- a = "tide", b = "dome", base = "modest"
- Output:
- "didesd"
- Explanation:
The pairs t~d, i~o, d~m, e~e give the groups {d, m, t}, {i, o} and {e};
modestbecomesdidesd.
Example 2
- Input:
- a = "abc", b = "abc", base = "cab"
- Output:
- "cab"
- Explanation:
Every letter is only paired with itself, so nothing changes.
Example 3
- Input:
- a = "pq", b = "qr", base = "rqpz"
- Output:
- "pppz"
- Explanation:
p~q and q~r put p, q and r in one group whose smallest letter is p; z is alone, so the result is
pppz.
Constraints
- 1 ≤ a.length = b.length ≤ 105
- 1 ≤ base.length ≤ 105
- a, b and base consist of lowercase English letters
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms
Expected complexity
- Time
- O(n + m)
- Space
- O(1)