Determine if Two Strings Are Close
Real-world version: Are the Two Words KinThe statement here is our own: the same inputs, outputs and technique.
Two words first and second hold only lowercase letters. Two moves are allowed on a word, each usable as often as you like:
- Swap the letters sitting at any two positions.
- Pick two letters that both already appear somewhere in the word and exchange them throughout: every copy of one becomes the other and every copy of the other becomes the first.
Call the words kin when some run of moves turns first into second.
Return true when they are kin.
Examples
Example 1
- Input
- first = "aaabb", second = "aabbb"
- Output
- true
Exchanging every a with every b turns the first word into three b and two a, and rearranging those gives the second word.
Example 2
- Input
- first = "aaab", second = "aabb"
- Output
- false
Both words use only a and b, but the first holds three a and one b while the second holds two of each, and no move can change a tally's value.
Example 3
- Input
- first = "aab", second = "bbc"
- Output
- false
The first word uses an a and the second does not, and no move can bring in a letter that is not already present.
Constraints
- 1 <= first.length <= 10^5
- 1 <= second.length <= 10^5
- first and second hold only lowercase English letters
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def close_strings(first: str, second: str) -> bool:public boolean closeStrings(String first, String second)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's