All problems
1114MediumHash TableStringSortingCounting

Are the Two Words Kin

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1657Determine if Two Strings Are Close

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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