Lexicographically Smallest Equivalent String - Problem

You are given two strings of the same length s1 and s2 and a string baseStr.

We say s1[i] and s2[i] are equivalent characters. For example, if s1 = "abc" and s2 = "cde", then we have 'a' == 'c', 'b' == 'd', and 'c' == 'e'.

Equivalent characters follow the usual rules of any equivalence relation:

  • Reflexivity: 'a' == 'a'
  • Symmetry: 'a' == 'b' implies 'b' == 'a'
  • Transitivity: 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'

For example, given the equivalency information from s1 = "abc" and s2 = "cde", "acd" and "aab" are equivalent strings of baseStr = "eed", and "aab" is the lexicographically smallest equivalent string of baseStr.

Return the lexicographically smallest equivalent string of baseStr by using the equivalency information from s1 and s2.

Input & Output

Example 1 — Basic Case
$ Input: s1 = "abc", s2 = "cde", baseStr = "eed"
Output: "aab"
💡 Note: Equivalencies: 'a'=='c', 'b'=='d', 'c'=='e'. By transitivity: 'a'=='c'=='e', so group {a,c,e} has root 'a'. Group {b,d} has root 'b'. So "eed" becomes "aab".
Example 2 — Self Equivalency
$ Input: s1 = "leetcode", s2 = "programs", baseStr = "sourcecode"
Output: "aauaaaaada"
💡 Note: Multiple character equivalencies create several groups. Each character in baseStr is replaced by its group's lexicographically smallest character.
Example 3 — No Changes
$ Input: s1 = "a", s2 = "b", baseStr = "xyz"
Output: "xyz"
💡 Note: Only 'a' and 'b' are equivalent. Characters 'x', 'y', 'z' in baseStr remain unchanged since they have no equivalencies.

Constraints

  • 1 ≤ s1.length, s2.length, baseStr.length ≤ 1000
  • s1.length == s2.length
  • s1, s2, and baseStr consist of lowercase English letters.

Visualization

Tap to expand
Lexicographically Smallest Equivalent Strings1 = "abc"s2 = "cde"baseStr = "eed"equivalenciesGroup 1: {a, c, e}Representative: 'a'Group 2: {b, d}Representative: 'b'Result: "aab"transform
Understanding the Visualization
1
Input
s1="abc", s2="cde", baseStr="eed"
2
Group Characters
Form equivalency groups: {a,c,e} and {b,d}
3
Transform
Replace each character with group's smallest: "aab"
Key Takeaway
🎯 Key Insight: Use Union-Find to efficiently group equivalent characters and find the lexicographically smallest representative for each group
Asked in
Google 25 Amazon 18 Facebook 15
32.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen