#2531
Medium Algorithms Make number of distinct characters equal
Hash Table String Counting
27.5% acceptance
Feb 25, 2026
609
160
You are given two 0-indexed strings word1 and word2.
A move consists of choosing two indices i and j such that 0 <= i < word1.length
and 0 <= j < word2.length and swapping word1[i] with word2[j].
Return true if it is possible to get the number of distinct characters in word1
and word2 to be equal with exactly one move. Return false otherwise.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn is_it_possible(word1: String, word2: String) -> bool {
let mut freq1 = [0i32; 26];
let mut freq2 = [0i32; 26];
for b in word1.bytes() {
freq1[(b - b'a') as usize] += 1;
}
for b in word2.bytes() {
freq2[(b - b'a') as usize] += 1;
}
let d1 = freq1.iter().filter(|&&x| x > 0).count() as i32;
let d2 = freq2.iter().filter(|&&x| x > 0).count() as i32;
for c1 in 0..26 {
if freq1[c1] == 0 {
continue;
}
for c2 in 0..26 {
if freq2[c2] == 0 {
continue;
}
if c1 == c2 {
if d1 == d2 {
return true;
}
continue;
}
// Remove c1 from word1, add c2 to word1
let mut new_d1 = d1;
if freq1[c1] == 1 {
new_d1 -= 1;
}
if freq1[c2] == 0 {
new_d1 += 1;
}
// Remove c2 from word2, add c1 to word2
let mut new_d2 = d2;
if freq2[c2] == 1 {
new_d2 -= 1;
}
if freq2[c1] == 0 {
new_d2 += 1;
}
if new_d1 == new_d2 {
return true;
}
}
}
false
}
}