#1657
Medium Algorithms Determine if two strings are close
Hash Table String Sorting Counting
54.2% acceptance
Feb 25, 2026
4112
356
Two strings are considered close if you can attain one from the other using:
Operation 1: Swap any two existing characters.
Operation 2: Transform every occurrence of one existing character into another
existing character, and do the same with the other character.
Given two strings, word1 and word2, return true if word1 and word2 are close.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn close_strings(word1: String, word2: String) -> bool {
let mut f1 = [0i32; 26];
let mut f2 = [0i32; 26];
for b in word1.bytes() {
f1[(b - b'a') as usize] += 1;
}
for b in word2.bytes() {
f2[(b - b'a') as usize] += 1;
}
// Same character presence
for i in 0..26 {
if (f1[i] == 0) != (f2[i] == 0) {
return false;
}
}
// Same multiset of frequencies
let mut v1: Vec<i32> = f1.into_iter().filter(|&x| x > 0).collect();
let mut v2: Vec<i32> = f2.into_iter().filter(|&x| x > 0).collect();
v1.sort_unstable();
v2.sort_unstable();
v1 == v2
}
}