Skip to content

1061. Lexicographically Smallest Equivalent String 👍

  • Time: $O(|\texttt{s1}| + |\texttt{baseStr}|)$
  • Space: $O(26 + |\texttt{baseStr}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class UnionFind {
 public:
  UnionFind(int n) : id(n) {
    iota(id.begin(), id.end(), 0);
  }

  void union_(int u, int v) {
    const int i = find(u);
    const int j = find(v);
    if (i > j)
      id[i] = j;
    else
      id[j] = i;
  }

  int find(int u) {
    return id[u] == u ? u : id[u] = find(id[u]);
  }

 private:
  vector<int> id;
};

class Solution {
 public:
  string smallestEquivalentString(string s1, string s2, string baseStr) {
    string ans;
    UnionFind uf(26);

    for (int i = 0; i < s1.length(); ++i)
      uf.union_(s1[i] - 'a', s2[i] - 'a');

    for (const char c : baseStr)
      ans += 'a' + uf.find(c - 'a');

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class UnionFind {
  public UnionFind(int n) {
    id = new int[n];
    for (int i = 0; i < n; ++i)
      id[i] = i;
  }

  public void union(int u, int v) {
    final int i = find(u);
    final int j = find(v);
    if (i > j)
      id[i] = j;
    else
      id[j] = i;
  }

  public int find(int u) {
    return id[u] == u ? u : (id[u] = find(id[u]));
  }

  private int[] id;
}

class Solution {
  public String smallestEquivalentString(String s1, String s2, String baseStr) {
    StringBuilder sb = new StringBuilder();
    UnionFind uf = new UnionFind(26);

    for (int i = 0; i < s1.length(); ++i)
      uf.union(s1.charAt(i) - 'a', s2.charAt(i) - 'a');

    for (final char c : baseStr.toCharArray())
      sb.append((char) ('a' + uf.find(c - 'a')));

    return sb.toString();
  }
}