Buddy Strings
💻 coding

Buddy Strings

1 min read 241 words
1 min read
ShareWhatsAppPost on X
  • 1To determine if two strings A and B can be made equal by swapping two letters in A, they must have the same length.
  • 2The function returns true if exactly two characters differ between A and B, or if all characters are the same with duplicates.
  • 3The solution has a time complexity of O(n) and a space complexity of O(n), making it efficient for strings up to 20,000 characters.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"To determine if two strings A and B can be made equal by swapping two letters in A, they must have the same length."

Buddy Strings

Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.

Example 1:

Input: A = "ab", B = "ba"

Output: true

Example 2:

Input: A = "ab", B = "ab"

Output: false

Example 3:

Input: A = "aa", B = "aa"

Output: true

Example 4:

Input: A = "aaaaaaabc", B = "aaaaaaacb"

Output: true

Example 5:

Input: A = "", B = "aa"

Output: false

Note:

0 <= A.length <= 20000

0 <= B.length <= 20000

A and B consist only of lowercase letters.

Solution:

using System;
using System.Collections.Generic;

namespace NetCoreCoding.LeetCode.String.Easy
{
 public class BuddyStringsSoln
 {
 public BuddyStringsSoln()
 {
 }

 public void execute()
 {
 var A = "abab";
 var B = "abab";
 var res = BuddyStrings(A,B);
 }

 public bool BuddyStrings(string A, string B)
 {
 if (A.Length != B.Length)
 return false;

 int diff = 0;
 char[] diffChar = new char[2];
 var set = new HashSet<char>();
 for (int i = 0; i < A.Length; i++)
 {
 if (A[i] != B[i])
 {
 diff++;
 if(diff==1)
 {
 diffChar[0] = A[i];
 diffChar[1] = B[i];
 }
 else
 {
 if (diffChar[0] != B[i] || diffChar[1] != A[i])
 return false;
 }
 }
 
 set.Add(A[i]);
 }

 if (A == B)
 return set.Count < A.Length;

 //case where all characters are same in 
 if (diff == 0 && set.Count == 1)
 return true;

 return diff == 2;
 }
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 7 May 2020 · 1 min read · 241 words

Part of AskGif Blog · coding

You might also like