LeetCode Entry

1790. Check if One String Swap Can Make Strings Equal

05.02.2025 easy 2025 kotlin rust

One swap to make stings equal

1790. Check if One String Swap Can Make Strings Equal easy blog post substack youtube 1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/886

Problem TLDR

One swap to make stings equal #easy

Intuition

Find all differences, then analyze them. Or do a single swap, then compare strings.

Approach

  • zip - unzip is a good match here

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\) or O(n) for Kotlin/Rust worst

Code


    fun areAlmostEqual(s1: String, s2: String) =
        s1.zip(s2).filter { (a, b) -> a != b }.unzip()
        .let { (a, b) -> a.size < 3 && a == b.reversed() }


    pub fn are_almost_equal(s1: String, s2: String) -> bool {
        let (a, mut b): (Vec<_>, Vec<_>) = s1.bytes().zip(s2.bytes())
        .filter(|(a, b)| a != b).unzip(); b.reverse(); a.len() < 3 && a == b
    }


    bool areAlmostEqual(string s1, string s2) {
        for (int i = 0, j = -1, c = 0; i < size(s1) && !c; ++i)
            if (s1[i] != s2[i]) j < 0 ? j = i : (swap(s1[j], s1[i]),++c);
        return s1 == s2;
    }