Buddy Strings

Given two strings s and goal, return true if you can swap exactly two letters in s (at two different indices) so that the result equals goal, and false otherwise.

30:00

Buddy Strings
easy
Free written solution
Topics
Companies

Given two strings s and goal, return true if you can swap exactly two letters in s (at two different indices) so that the result equals goal, and false otherwise.

Example 1:
Input: {"s":"ab","goal":"ba"}
Output: true
Constraints:
  • 1≤s.length,goal.length≤2×1041 \leq s.\text{length}, \text{goal.length} \leq 2 \times 10^4

  • s and goal consist of lowercase letters.

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

Run code to see results.

Input
arr ={"s":"ab","goal":"ba"}

A swap keeps the length, so first compare len(s) = 2 with len(goal) = 2.

s over goal

0

1

s

a
b

goal

b
a

diffs =

slot
slot

one swap can fix exactly two slots

Variables
VariableValue
len(s)2
len(goal)2
DepthFunction Call
Stack empty
0/7