09 Sept 2026Go / Python / TypeScriptEasy

Buddy Strings

Check whether swapping exactly two characters in one string can produce another string.

For equal strings, require a repeated character. Otherwise collect mismatch positions and verify that exactly two cross-match.

complexity

O(n) time and O(1) space for a fixed alphabet.

solution files

  • Go buddy-strings/solution.go
  • Python buddy-strings/solution.py
  • TypeScript buddy-strings/solution.ts

Solution files

Gobuddy-strings/solution.go
package main

func buddyStrings(s string, goal string) bool {
	if len(s) != len(goal) {
		return false
	}
	if s == goal {
		seen := map[byte]bool{}
		for index := range s {
			if seen[s[index]] {
				return true
			}
			seen[s[index]] = true
		}
		return false
	}
	mismatch := []int{}
	for index := range s {
		if s[index] != goal[index] {
			mismatch = append(mismatch, index)
		}
	}
	return len(mismatch) == 2 && s[mismatch[0]] == goal[mismatch[1]] && s[mismatch[1]] == goal[mismatch[0]]
}
Pythonbuddy-strings/solution.py
class Solution:
    def buddyStrings(self, s: str, goal: str) -> bool:
        if len(s) != len(goal): return False
        if s == goal: return len(set(s)) < len(s)
        mismatch = [index for index in range(len(s)) if s[index] != goal[index]]
        return len(mismatch) == class="syntax-number">2 and s[mismatch[class="syntax-number">0]] == goal[mismatch[class="syntax-number">1]] and s[mismatch[class="syntax-number">1]] == goal[mismatch[class="syntax-number">0]]
TypeScriptbuddy-strings/solution.ts
function buddyStrings(s: string, goal: string): boolean {
  if (s.length !== goal.length) return false;
  if (s === goal) return new Set(s).size < s.length;
  const mismatch: number[] = [];
  for (let index = class="syntax-number">0; index < s.length; index += class="syntax-number">1) if (s[index] !== goal[index]) mismatch.push(index);
  return mismatch.length === class="syntax-number">2 && s[mismatch[class="syntax-number">0]] === goal[mismatch[class="syntax-number">1]] && s[mismatch[class="syntax-number">1]] === goal[mismatch[class="syntax-number">0]];
}