InterviewPrepKit

Home / Coding / Arrays & Hashing

Determine if Two Strings Are Close

medium Original β†—
Solving tips
  • Don't simulate the operations; characterize their invariants (what they cannot change).
  • Swaps make order irrelevant and transforms shuffle which letter owns which count, so two strings are close iff they share the same letter SET and the same sorted multiset of frequencies.
  • Both conditions are required: sorted frequencies alone fails 'aab' vs 'bbc'; matching letter sets alone fails 'a' vs 'aa'.
  • Use Counter or a fixed 26-int array; target O(n) time and O(1) space (26-letter alphabet).

Problem

Two strings are close if you can turn one into the other using any sequence of these two operations:

  1. Swap any two characters of the string (e.g. abcde β†’ aecdb).
  2. Transform one existing character into another existing character, applying it to every occurrence of both simultaneously (e.g. aacabb β†’ bbcbaa: every a becomes b and every b becomes a).

Given word1 and word2, return True if they are close, False otherwise.

Examples

  • word1 = "abc", word2 = "bca" β†’ True β€” operation 1 alone can produce any rearrangement.
  • word1 = "a", word2 = "aa" β†’ False β€” no operation changes the length.
  • word1 = "cabbba", word2 = "abbccc" β†’ True β€” cabbba has aΓ—2, bΓ—3, cΓ—1 and abbccc has aΓ—1, bΓ—2, cΓ—3: same character set {a, b, c}, same sorted frequencies [1, 2, 3], so transforms plus swaps can bridge them.

Constraints

  • 1 <= word1.length, word2.length <= 10^5
  • Lowercase English letters only.

Searching over operation sequences is hopeless at this size β€” you need to find what the operations preserve.

Think about it first

Hint 1 Operation 1 means character order never matters. What single object fully describes a string once order is irrelevant?
Hint 2 Operation 2 exchanges the frequency counts of two characters that are both present β€” it can shuffle *which letter owns which count*, but what two things can it never change?
Hint 3 Two strings are close iff (a) they use exactly the same *set* of letters, and (b) their sorted lists of letter frequencies are identical. Compare `set(word)` and `sorted(Counter(word).values())` for both.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.