Show problems as
Classic problem #1657MediumHash TableStringSortingCounting

Determine if Two Strings Are Close

Real-world version: Are the Two Words Kin
Tracked in this browser only
Read Determine if Two Strings Are Close on LeetCode(opens in a new tab)

The 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.

Python
def close_strings(first: str, second: str) -> bool:
Java
public boolean closeStrings(String first, String second)