LeetCode 2531: Make Number of Distinct Characters Equal Solution
Master LeetCode problem 2531 (Make Number of Distinct Characters Equal), 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.
2531. Make Number of Distinct Characters Equal
Problem Explanation
Explanation:
To determine if it is possible to make the number of distinct characters in word1 and word2 equal with exactly one move, we need to consider the following cases:
- If the total number of distinct characters in both strings is already equal, return true.
- If the difference between the number of distinct characters in
word1andword2is more than 1, return false. - If the difference is exactly 1, we can achieve the goal with one swap.
Algorithm:
- Count the occurrences of each character in
word1andword2. - Calculate the number of distinct characters in
word1andword2. - If the number of distinct characters in both strings is the same, return true.
- If the difference is more than 1, return false.
- If the difference is exactly 1, check if one of the strings contains a character that is not present in the other string. If found, return true; otherwise, return false.
Time Complexity: O(n) Space Complexity: O(1)
:
Solution Code
class Solution {
public boolean makeEqual(String word1, String word2) {
int[] count1 = new int[26];
int[] count2 = new int[26];
for (char c : word1.toCharArray()) {
count1[c - 'a']++;
}
for (char c : word2.toCharArray()) {
count2[c - 'a']++;
}
int distinct1 = 0, distinct2 = 0;
for (int count : count1) {
if (count > 0) distinct1++;
}
for (int count : count2) {
if (count > 0) distinct2++;
}
if (distinct1 == distinct2) {
return true;
}
if (Math.abs(distinct1 - distinct2) > 1) {
return false;
}
if (distinct1 > distinct2) {
return checkDistinct(count1, count2);
} else {
return checkDistinct(count2, count1);
}
}
private boolean checkDistinct(int[] count1, int[] count2) {
for (int i = 0; i < 26; i++) {
if (count1[i] > 0 && count2[i] == 0) {
return true;
}
}
return false;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2531 (Make Number of Distinct Characters Equal)?
This page provides optimized solutions for LeetCode problem 2531 (Make Number of Distinct Characters Equal) 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 2531 (Make Number of Distinct Characters Equal)?
The time complexity for LeetCode 2531 (Make Number of Distinct Characters Equal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2531 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2531 in Java, C++, or Python.