Skip to main content
Back to problems
#859
Easy Algorithms

Buddy strings

Hash Table String
33.9% acceptance
Feb 22, 2026
3348
1849
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".

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
/*
 * 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.
 */

impl Solution {
  pub fn buddy_strings(s: String, goal: String) -> bool {
    if s.len() != goal.len() { return false; }
    let sb = s.as_bytes();
    let gb = goal.as_bytes();
    let diffs: Vec<usize> = (0..sb.len()).filter(|&i| sb[i] != gb[i]).collect();
    if diffs.is_empty() {
      // Need a repeated character to swap
      let mut seen = [false; 26];
      return sb.iter().any(|&b| {
        let idx = (b - b'a') as usize;
        let r = seen[idx];
        seen[idx] = true;
        r
      });
    }
    diffs.len() == 2 && sb[diffs[0]] == gb[diffs[1]] && sb[diffs[1]] == gb[diffs[0]]
  }
}