Determine if Two Strings Are Close

Two strings are close if one can be turned into the other using these operations any number of times: (1) swap any two existing characters, for example abcde -> aecdb; (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 become b's and all b's become a's). Given `word1` and `word2`, return true if they are close and false otherwise.

30:00

Determine if Two Strings Are Close
medium
Free written solution
Topics
Companies

Two strings are close if one can be turned into the other using these operations any number of times: (1) swap any two existing characters, for example abcde -> aecdb; (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 become b's and all b's become a's). Given word1 and word2, return true if they are close and false otherwise.

Example 1:
Input: {"word1":"abc","word2":"bca"}
Output: true
Constraints:
  • 1 <= word1.length, word2.length <= 10^5

  • word1 and word2 contain only lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"word1":"abc","word2":"bca"}

Operation 1 swaps two characters and operation 2 swaps the roles of two letters that both exist. Find what neither operation can change, then compare that between "abc" and "bca".

the two words

length 3 vs 3

word1

a
b
c

word2

b
c
a

letter counts (both words must use the same letters)

Nothing counted yet.

■ word1

■ word2

counts sorted, letters forgotten (relabeling)

Reached only after the lengths and the letter sets both match.

Variables
VariableValue
len(word1)3
len(word2)3
DepthFunction Call
Stack empty
0/16