Skip to content
Problem 1657 · LeetCode 1657(opens in a new tab)

Determine if Two Strings Are Close

MediumHash tables

You may change a word with two kinds of move, as often as you like. The first swaps the letters at any two positions. The second picks two letters that both appear in the word and renames them into each other: every copy of the first becomes the second, and every copy of the second becomes the first.

Call two words close when these moves can turn one into the other. Given word1 and word2, return true if they are close and false if not.

Example 1

Input:  word1 = "aab", word2 = "bba"
Output: true
Why:    rename a and b into each other, then reorder
2 more examples and the constraints

Example 2

Input:  word1 = "abc", word2 = "abd"
Output: false
Why:    no move can create the letter d

Example 3

Input:  word1 = "aabccc", word2 = "abbbcc"
Output: true
Why:    same letters, and counts 2, 1, 3 can be shuffled to 1, 3, 2

Constraints

  • 1 ≤ word1.length, word2.length ≤ 100,000
  • Both words use only lowercase English letters

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort and compare runsO(n log n)
  2. Count into 26 slotsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 lettersVerdict
Sort and compare runsO(n log n)
Passes; sorting is extra work
Count into 26 slotsO(n)
Best; one pass per word

n = length of the words. The alphabet has 26 letters, so sorting the counts is constant work.

Edge cases to test

  • Different lengths. "z" and "zz" can never be close: no move changes the length.
  • A letter in only one word. "ab" and "aa" have the same length, but b cannot be removed, so the answer is false.
  • Same letters, other counts. "aabb" and "aaab" share a and b, but the counts 2, 2 and 3, 1 differ.
  • Identical words. Zero moves are allowed, so a word is always close to itself.

Common mistakes

  • Comparing only the sorted counts and forgetting that both words need the same letters.
  • Comparing only the letter sets and forgetting the counts.
  • Comparing the counts letter by letter without sorting, which misses the renaming move.

How to talk through it

  1. 1Clarify. Lowercase letters only? Can the words differ in length?
  2. 2Name what the moves keep. Swaps make order irrelevant; renaming shuffles counts among letters already present.
  3. 3State the two conditions. Same set of letters, and the same counts once both lists are sorted.
  4. 4Code it with 26 slots. Check lengths, count, compare zero patterns, sort and compare.
  5. 5Test out loud. Run different lengths, "ab" against "ac" and a pair that needs a rename.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?