Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
Two strings are considered close if you can attain one from the other using the following operations:
abcde -> aecdbaacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)You can use the operations on either string as many times as necessary.
Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.
Example 1:
Input: word1 = "abc", word2 = "bca" Output: true Explanation: You can attain word2 from word1 in 2 operations. Apply Operation 1: "abc" -> "acb" Apply Operation 1: "acb" -> "bca"
Example 2:
Input: word1 = "a", word2 = "aa" Output: false Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
Example 3:
Input: word1 = "cabbba", word2 = "abbccc" Output: true Explanation: You can attain word2 from word1 in 3 operations. Apply Operation 1: "cabbba" -> "caabbb" Apply Operation 2: "caabbb" -> "baaccc" Apply Operation 2: "baaccc" -> "abbccc"
Constraints:
1 <= word1.length, word2.length <= 105word1 and word2 contain only lowercase English letters.Problem summary: Two strings are considered close if you can attain one from the other using the following operations: Operation 1: Swap any two existing characters. For example, abcde -> aecdb Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's) You can use the operations on either string as many times as necessary. Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map
"abc" "bca"
"a" "aa"
"cabbba" "abbccc"
buddy-strings)minimum-swaps-to-make-strings-equal)minimum-number-of-steps-to-make-two-strings-anagram)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1657: Determine if Two Strings Are Close
class Solution {
public boolean closeStrings(String word1, String word2) {
int[] cnt1 = new int[26];
int[] cnt2 = new int[26];
for (int i = 0; i < word1.length(); ++i) {
++cnt1[word1.charAt(i) - 'a'];
}
for (int i = 0; i < word2.length(); ++i) {
++cnt2[word2.charAt(i) - 'a'];
}
for (int i = 0; i < 26; ++i) {
if ((cnt1[i] == 0) != (cnt2[i] == 0)) {
return false;
}
}
Arrays.sort(cnt1);
Arrays.sort(cnt2);
return Arrays.equals(cnt1, cnt2);
}
}
// Accepted solution for LeetCode #1657: Determine if Two Strings Are Close
func closeStrings(word1 string, word2 string) bool {
cnt1 := make([]int, 26)
cnt2 := make([]int, 26)
for _, c := range word1 {
cnt1[c-'a']++
}
for _, c := range word2 {
cnt2[c-'a']++
}
if !slices.EqualFunc(cnt1, cnt2, func(v1, v2 int) bool { return (v1 == 0) == (v2 == 0) }) {
return false
}
sort.Ints(cnt1)
sort.Ints(cnt2)
return slices.Equal(cnt1, cnt2)
}
# Accepted solution for LeetCode #1657: Determine if Two Strings Are Close
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
cnt1, cnt2 = Counter(word1), Counter(word2)
return sorted(cnt1.values()) == sorted(cnt2.values()) and set(
cnt1.keys()
) == set(cnt2.keys())
// Accepted solution for LeetCode #1657: Determine if Two Strings Are Close
impl Solution {
pub fn close_strings(word1: String, word2: String) -> bool {
let mut cnt1 = vec![0; 26];
let mut cnt2 = vec![0; 26];
for c in word1.chars() {
cnt1[((c as u8) - b'a') as usize] += 1;
}
for c in word2.chars() {
cnt2[((c as u8) - b'a') as usize] += 1;
}
for i in 0..26 {
if (cnt1[i] == 0) != (cnt2[i] == 0) {
return false;
}
}
cnt1.sort();
cnt2.sort();
cnt1 == cnt2
}
}
// Accepted solution for LeetCode #1657: Determine if Two Strings Are Close
function closeStrings(word1: string, word2: string): boolean {
const cnt1 = Array(26).fill(0);
const cnt2 = Array(26).fill(0);
for (const c of word1) {
++cnt1[c.charCodeAt(0) - 'a'.charCodeAt(0)];
}
for (const c of word2) {
++cnt2[c.charCodeAt(0) - 'a'.charCodeAt(0)];
}
for (let i = 0; i < 26; ++i) {
if ((cnt1[i] === 0) !== (cnt2[i] === 0)) {
return false;
}
}
cnt1.sort((a, b) => a - b);
cnt2.sort((a, b) => a - b);
return cnt1.join('.') === cnt2.join('.');
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan the rest of the array looking for a match. Two nested loops give n × (n−1)/2 comparisons = O(n²). No extra space since we only use loop indices.
One pass through the input, performing O(1) hash map lookups and insertions at each step. The hash map may store up to n entries in the worst case. This is the classic space-for-time tradeoff: O(n) extra memory eliminates an inner loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.