InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Determine if Two Strings Are Close

medium Original ↗ 00:00

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. abcdeaecdb).
  2. Transform one existing character into another existing character, applying it to every occurrence of both simultaneously (e.g. aacabbbbcbaa: 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"Truecabbba 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 infeasible at this size. The solution comes from identifying 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug