Magicsheet logo

Determine if Two Strings Are Close

Medium
100%
Updated 6/1/2025

Determine if Two Strings Are Close

What is this problem about?

Two strings are "close" if you can transform one into the other using two operations:

  1. Swap any two characters (essentially allows any permutation).
  2. Transform all occurrences of one character into another character and vice-versa (e.g., all 'a's become 'b's and all 'b's become 'a's). The Determine if Two Strings Are Close coding problem asks you to return true if the strings can be made equal.

Why is this asked in interviews?

This "Medium" problem is popular at Apple and Microsoft because it tests your ability to identify invariants. It evaluations whether you can see past the "operations" to the underlying mathematical properties that must remain true. It’s a test of hash table interview patterns and sorting for frequency analysis.

Algorithmic pattern used

Two strings are close if and only if:

  1. They have the same length.
  2. They have the same set of unique characters (since operation 2 only swaps frequencies between existing characters).
  3. The sorted list of their character frequencies is the same.

Example explanation

String 1: "cabbba", String 2: "abbccc".

  1. Lengths match (6).
  2. Unique characters: String 1 {a, b, c}, String 2 {a, b, c}. Match.
  3. Frequencies String 1: a:2, b:3, c:1. Sorted: [1, 2, 3].
  4. Frequencies String 2: a:1, b:2, c:3. Sorted: [1, 2, 3].
  5. All conditions met. Result: true.

Common mistakes candidates make

  • Missing Condition 2: Forgetting to check if both strings have the same unique character set (e.g., "abc" and "def" have same frequencies [1,1,1] but are not close).
  • Brute Force: Trying to actually simulate the swaps and transformations, which is impossible due to the sheer number of combinations.
  • Length Check: Forgetting to check the length at the start.

Interview preparation tip

Whenever a problem gives you "unlimited swaps," it means the order of characters doesn't matter—only the counts do. This immediately tells you to use a frequency map or an array of size 26.

Similar Questions