Skip to content

Determine if Two Strings Are Close

MediumArrays & Hashing
Decode it first. Clues, constraints, pattern and plan before any code.

Two strings are close if you can turn one into the other using these moves as many times as you like:

  1. Swap any two characters (positions do not matter): abc → cba.
  2. Swap the roles of two letters that both exist: every a becomes b and every b becomes a. For example aacabb → bbcbaa.

Given word1 and word2, return true if they are close.

word1 = "abc",    word2 = "bca"      →  true
word1 = "a",      word2 = "aa"       →  false
word1 = "cabbba", word2 = "abbccc"   →  true

Constraints

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