LeetCode 1061: Lexicographically Smallest Equivalent String Solution
Master LeetCode problem 1061 (Lexicographically Smallest Equivalent String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1061. Lexicographically Smallest Equivalent String
Problem Explanation
Explanation:
To solve this problem, we can use the concept of disjoint sets (union-find). We first initialize a parent array where each character is its own parent. Then, we iterate through the equivalency information provided by s1 and s2 to union the equivalent characters. Finally, we iterate through baseStr and find the root parent of each character and construct the lexicographically smallest equivalent string.
- Initialize the parent array where each character is its own parent.
- Iterate through
s1ands2, union the equivalent characters. - Iterate through
baseStr, find the root parent of each character. - Construct the lexicographically smallest equivalent string.
Time complexity: O(n + m + kα(n)), where n is the length of s1, m is the length of s2, k is the length of baseStr, and α(n) is the inverse Ackermann function, which is very slow-growing.
Space complexity: O(26) = O(1) for the parent array.
Solution Code
class Solution {
public String smallestEquivalentString(String s1, String s2, String baseStr) {
char[] parent = new char[26];
for (char c = 'a'; c <= 'z'; c++) {
parent[c - 'a'] = c;
}
for (int i = 0; i < s1.length(); i++) {
char root1 = findRoot(parent, s1.charAt(i));
char root2 = findRoot(parent, s2.charAt(i));
if (root1 != root2) {
parent[root1 - 'a'] = root2;
}
}
StringBuilder sb = new StringBuilder();
for (char c : baseStr.toCharArray()) {
sb.append(findRoot(parent, c));
}
return sb.toString();
}
private char findRoot(char[] parent, char c) {
if (parent[c - 'a'] == c) {
return c;
}
return findRoot(parent, parent[c - 'a']);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1061 (Lexicographically Smallest Equivalent String)?
This page provides optimized solutions for LeetCode problem 1061 (Lexicographically Smallest Equivalent String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1061 (Lexicographically Smallest Equivalent String)?
The time complexity for LeetCode 1061 (Lexicographically Smallest Equivalent String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1061 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1061 in Java, C++, or Python.