Determine if Two Strings Are Close - Problem

Two strings are considered close if you can attain one from the other using the following operations:

Operation 1: Swap any two existing characters.

For example, abcde → aecdb

Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.

For example, aacabb → bbcbaa (all a's turn into b's, and all b's turn into a's)

You can use the operations on either string as many times as necessary.

Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.

Input & Output

Example 1 — Basic Character Swap
$ Input: word1 = "abc", word2 = "bca"
Output: true
💡 Note: Both strings have same characters {a,b,c} and same frequency distribution [1,1,1]. We can transform abc → bca using swaps and character transformations.
Example 2 — Different Characters
$ Input: word1 = "a", word2 = "aa"
Output: false
💡 Note: Different lengths and word2 has frequency [2] while word1 has frequency [1]. Cannot make them close.
Example 3 — Character Transformation
$ Input: word1 = "cabbba", word2 = "abbccc"
Output: false
💡 Note: Both have characters {a,b,c}. word1 frequencies: c=1,a=1,b=4 → sorted [1,1,4]. word2 frequencies: a=1,b=2,c=4 → sorted [1,2,4]. Different frequency distributions [1,1,4] vs [1,2,4], so they cannot be made close.

Constraints

  • 1 ≤ word1.length, word2.length ≤ 105
  • word1 and word2 contain only lowercase English letters.

Visualization

Tap to expand
Determine if Two Strings Are Close INPUT word1 = "abc" a b c word2 = "bca" b c a Character Sets: {a, b, c} {a, b, c} Frequencies: [1, 1, 1] [1, 1, 1] (sorted) ALGORITHM STEPS 1 Check Lengths len(abc) = len(bca) = 3 OK - Equal 2 Get Character Sets set1 = {a, b, c} set2 = {a, b, c} 3 Compare Sets set1 == set2? OK - Same chars 4 Compare Frequencies sorted([1,1,1]) == sorted([1,1,1])? OK - Same freqs Sorted Frequencies Match: [1, 1, 1] = [1, 1, 1] FINAL RESULT true Strings are CLOSE! Why they are close: 1. Same length: 3 2. Same char set: {a,b,c} 3. Same freq pattern: [1, 1, 1] Can swap: abc --> bca (using Operation 1) Key Insight: Two strings are close if and only if: 1. They have the SAME SET of characters (Operation 2 can only swap existing chars) 2. They have the SAME SORTED FREQUENCY array (Op 2 swaps frequencies, Op 1 rearranges) Time: O(n) Space: O(1) (26 char alphabet) TutorialsPoint - Determine if Two Strings Are Close | Optimized Character Set + Frequency Check
Asked in
Google 15 Microsoft 12 Amazon 8
85.4K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen