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".
s and goal always have the same length for a valid swap to be possible?
s and goal are not the same, a valid swap cannot make them equal.Length Check: First, check if the lengths of s and goal are different. If they are, we can immediately return false.
Identical Strings Handling: If the strings s and goal are identical, we need to check if there is at least one character that appears more than once in s. This will allow us to perform a valid swap without changing the string.
Different Strings: If the strings are not identical:
s and goal. Collect all the indices where the characters are different.def buddy_strings(s: str, goal: str) -> bool:
# Step 1: Length check
if len(s) != len(goal):
return False
# Step 2: Check for identical strings
if s == goal:
seen = set()
for char in s:
if char in seen:
return True
seen.add(char)
return False
# Step 3: Compare differences
pairs = []
for i in range(len(s)):
if s[i] != goal[i]:
pairs.append((s[i], goal[i]))
if len(pairs) > 2:
return False
return len(pairs) == 2 and pairs[0] == pairs[1][::-1]
# Example usage:
print(buddy_strings("ab", "ba")) # Should return True
print(buddy_strings("ab", "ab")) # Should return False
print(buddy_strings("aa", "aa")) # Should return True
print(buddy_strings("aaaaaaabc", "aaaaaaacb")) # Should return True
print(buddy_strings("", "aa")) # Should return False
Thus, the overall time complexity of this solution is O(n), where n is the length of the input strings.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?