Leetcode - Buddy Strings Solution
1 min read

Leetcode - Buddy Strings Solution

Given two strings a and b, return true if you can swap two letters in a so the result is equal to b, 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 a[i] and a[j].

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

Example 1:

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

Example 2:

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

Example 3:

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

Example 4:

Input: a = "aaaaaaabc", b = "aaaaaaacb"
Output: true

Constraints:

  • 1 <= a.length, b.length <= 2 * 104
  • a and b consist of lowercase letters.

Solution in Python

class Solution:
    def buddyStrings(self, a: str, b: str) -> bool:
        diff = [(i,j) for i,j in zip(a,b) if i!=j]
        freq = Counter(a)
        if len(a) != len(b):
            return False
        if len(diff) == 2 and diff[0][0] == diff[1][1] and diff[0][1]==diff[1][0]:
            return True
        elif len(diff) == 0 and any(map(lambda x: x>1, freq.values())):
            return True
        else:
            return False

Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×