Determine if Two Strings Are Close - Problem
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.
Input & Output
Example 1 — Basic Character Swap
$
Input:
word1 = "abc", word2 = "bca"
›
Output:
true
💡 Note:
Both strings have same characters {a,b,c} and same frequency distribution [1,1,1]. We can transform abc → bca using swaps and character transformations.
Example 2 — Different Characters
$
Input:
word1 = "a", word2 = "aa"
›
Output:
false
💡 Note:
Different lengths and word2 has frequency [2] while word1 has frequency [1]. Cannot make them close.
Example 3 — Character Transformation
$
Input:
word1 = "cabbba", word2 = "abbccc"
›
Output:
true
💡 Note:
Both have characters {a,b,c}. word1 frequencies: a=1,b=4,c=1 → [1,1,4]. word2 frequencies: a=1,b=2,c=4 → [1,2,4]. Same sorted pattern [1,1,4] vs [1,2,4] - different, so false. Wait, let me recalculate... word1 has a=1,b=4,c=1, word2 has a=1,b=2,c=4. These have same characters but different frequency distributions, so actually false.
Constraints
- 1 ≤ word1.length, word2.length ≤ 105
- word1 and word2 contain only lowercase English letters.
Visualization
Tap to expand
Understanding the Visualization
1
Input Strings
Two strings with potentially different character arrangements
2
Check Closeness
Verify same character sets and frequency patterns
3
Result
True if strings are close, false otherwise
Key Takeaway
🎯 Key Insight: Strings are close if they have identical character sets and matching frequency distributions
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code