Determine if Two Strings Are Close

MediumStringshashing

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Two strings are *close* if one can be turned into the other using any number of these operations: 1. Swap any two characters at different positions (so characters can be rearranged freely). 2. Pick two letters that both occur in the string and exchange every occurrence of one with the other (for example aabcc becomes ccbaa by exchanging a and c). Given word1 and word2, return true if they are close and false otherwise. Operations are applied to one string only; you cannot introduce a letter that does not already occur.

Examples

Input: word1 = "aab", word2 = "bba"
Output: true
Exchange all a and b in "aab" to get "bba".
Input: word1 = "abc", word2 = "abd"
Output: false
word2 uses d, which never occurs in word1.
Input: word1 = "aabbbc", word2 = "abbccc"
Output: true
Counts are a:2 b:3 c:1 versus a:1 b:2 c:3; both use letters {a,b,c} with count multiset {1,2,3}, so relabeling and rearranging works.

Constraints

  • 1 <= word1.length, word2.length <= 10^5
  • `word1` and `word2` contain only lowercase English letters

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More hashing problems