Skip to content

889. Buddy Strings

Hash Table String

Problem - Buddy Strings

Easy

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].

  • For example, swapping at indices 0 and 2 in "abcd" results in "cbad".

 

Example 1:

Input: s = "ab", goal = "ba"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.

Example 2:

Input: s = "ab", goal = "ab"
Output: false
Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.

Example 3:

Input: s = "aa", goal = "aa"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.

 

Constraints:

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

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def buddyStrings(self, s: str, goal: str) -> bool:
        m, n = len(s), len(goal)
        if m != n:
            return False

        count_s, count_goal = Counter(s), Counter(goal)
        if count_s != count_goal:
            return False

        diff = sum(s[i] != goal[i] for i in range(n))
        return diff == 2 or (diff == 0 and any(val > 1 for val in count_s.values()))

Submission Stats:

  • Runtime: 3 ms (42.52%)
  • Memory: 18 MB (46.41%)