Buddy Strings

Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal; otherwise, return false.

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].

Example 1
Inputs = "ab", goal = "ba"
Outputtrue
You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
Example 2
Inputs = "ab", goal = "ab"
Outputfalse
The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.

Constraints

  • 1 <= s.length, goal.length <= 2 * 10^4
  • s and goal consist of lowercase letters.

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate