Check if One String Swap Can Make Strings Equal

Easy Topics Company Tags

The strings s1 and s2 have equal length. You may swap two character positions in exactly one of the strings, at most once. The chosen positions may be the same, and you may also perform no swap. Return true if the strings can become equal, or false otherwise.

Example 1:

Input: s1 = "abcd"
s2 = "abdc"

Output: true

Explanation: Swap the characters at indices 2 and 3 in abcd to obtain abdc.

Example 2:

Input: s1 = "abc"
s2 = "abd"

Output: false

Explanation: The strings differ at one position. A swap only reorders existing characters, and abc has no d, so equality is impossible.

Example 3:

Input: s1 = "hello"
s2 = "hello"

Output: true

Explanation: The strings are already equal. Performing no swap is allowed.

Constraints:

  • 1 <= s1.length, s2.length <= 100
  • s1.length == s2.length
  • Both strings contain only lowercase English letters.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.