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:
false
💡 Note:
Both have characters {a,b,c}. word1 frequencies: c=1,a=1,b=4 → sorted [1,1,4]. word2 frequencies: a=1,b=2,c=4 → sorted [1,2,4]. Different frequency distributions [1,1,4] vs [1,2,4], so they cannot be made close.
Constraints
- 1 ≤ word1.length, word2.length ≤ 105
- word1 and word2 contain only lowercase English letters.
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code