Skip to main content
Back to problems
#1790
Easy Algorithms

Check if one string swap can make strings equal

Hash Table String Counting
49.5% acceptance
Feb 25, 2026
1705
87
You are given two strings s1 and s2. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn are_almost_equal(s1: String, s2: String) -> bool {
    let diffs: Vec<usize> = s1.bytes().zip(s2.bytes())
      .enumerate()
      .filter(|&(_, (a, b))| a != b)
      .map(|(i, _)| i)
      .collect();
    match diffs.len() {
      0 => true,
      2 => {
        let (i, j) = (diffs[0], diffs[1]);
        let b1 = s1.as_bytes();
        let b2 = s2.as_bytes();
        b1[i] == b2[j] && b1[j] == b2[i]
      }
      _ => false,
    }
  }
}