Talentd
FleetCode
Make and follow sheets.Sign in

Check if One String Swap Can Make Strings Equal solution and explanation

EasyCountingHash TableString5 min read49.5% acceptanceUpdated 9 Apr 2026
Check if One String Swap Can Make Strings Equal - Leetcode 1790 - PythonNeetCodeIO · 8:01 · 8K viewsWatch on YouTube
9 more videos on this problem
  1. Check if One String Swap Can Make Strings Equal - Leetcode 1790 - PythonNeetCodeIO · 8:01 · 8K views
  2. Check if One String Swap Can Make Strings Equal | 2 Approaches | Leetcode 1790 | codestorywithMIKcodestorywithMIK · 17:03 · 4K views
  3. Check if One String Swap Can Make Strings Equal | Leetcode 1790Techdose · 10:12 · 3K views
  4. 1790. Check if One String Swap Can Make Strings Equal (Leetcode Easy)Programming Live with Larry · 4:01 · 2K views
  5. 1790. Check if One String Swap Can Make Strings Equal | leetcode daily challenge | shashcode | dsaShashCode · 11:28 · 2K views
  6. 1790. Check if One String Swap Can Make Strings Equal | Simple ArraysAryan Mittal · 7:46 · 1K views
  7. How to Solve "1790 Check if One String Swap Can Make Strings Equal" on LeetCode? - JavascriptBecoming A Better Dev (with David) · 9:19 · 951 views
  8. 1790. Check if One String Swap Can Make Strings Equal || Java || Leetcode || HindiCoding Sphere · 7:13 · 464 views
  9. 1790. Check if One String Swap Can Make Strings Equal - LeetCode Pair Programming in JavaBecoming A Better Dev (with David) · 58:34 · 401 views
  10. Leetcode | 1790 Check If one String Swap Can Make Strings Equal | Java | Simple ApproachCakot Coding · 12:25 · 349 views

The problem

You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.

Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.

Example 1:

Input: s1 = "bank", s2 = "kanb"
Output: true
Explanation: For example, swap the first character with the last character of s2 to make "bank".

Example 2:

Input: s1 = "attack", s2 = "defend"
Output: false
Explanation: It is impossible to make them equal with one string swap.

Example 3:

Input: s1 = "kelb", s2 = "kelb"
Output: true
Explanation: The two strings are already equal, so no string swap operation is required.

Constraints:

  • 1 <= s1.length, s2.length <= 100
  • s1.length == s2.length
  • s1 and s2 consist of only lowercase English letters.

Approach overview

Problem Overview: Two strings s1 and s2 of equal length are given. Determine whether a single swap of two characters in one string can make both strings identical.

Approach 1: Counting Mismatches and Swapping (O(n) time, O(1) space)

Scan both strings once and record indices where characters differ. If there are more than two mismatches, a single swap cannot fix the strings. If exactly two mismatches exist at indices i and j, check whether swapping s1[i] and s1[j] makes the strings equal by verifying s1[i] == s2[j] and s1[j] == s2[i]. If there are zero mismatches, the strings are already equal and the answer is true. This approach works with a simple linear pass over the string, storing at most two indices, so the space usage stays constant.

Approach 2: Permutation Check on Two Mismatches (O(n) time, O(1) space)

Another way is to focus on the characters themselves instead of the indices. Iterate through both strings and collect characters that differ. If the mismatch list grows beyond two pairs, return false. When exactly two mismatches appear, check whether the pair forms a valid permutation: the first mismatch from s1 must match the second from s2 and vice versa. This treats the problem as a small permutation validation using ideas similar to hash table or counting checks, but with only two elements. The logic remains O(n) because each character is visited once.

Both strategies rely on the same key insight: only two positions can differ if a single swap is enough to fix the strings. Any additional mismatch immediately invalidates the condition. Because the algorithm performs a single pass with constant memory, it scales well even for long strings.

Recommended for interviews: The mismatch counting approach is the one interviewers typically expect. It demonstrates clear reasoning about constraints and avoids unnecessary data structures. Showing that you first detect mismatches and then validate the swap condition signals strong problem decomposition and clean O(n) implementation.

Approach 1: Counting Mismatches and Swapping

Approach: This approach involves iterating through the strings and identifying the positions where the characters differ (mismatch). If the number of mismatched positions is zero, the strings are already equal. If there are exactly two mismatched character positions (i, j), you check if swapping the characters at these positions in one of the strings makes the two strings equal.

def can_be_equal_by_one_swap(s1, s2):
    diff_indices = [i for i in range(len(s1)) if s1[i] != s2[i]]
    if len(diff_indices) == 0:
        return True
    if len(diff_indices) != 2:
        return False
    i, j = diff_indices
    return s1[i] == s2[j] and s1[j] == s2[i]

s1 = "bank"
s2 = "kanb"
print(can_be_equal_by_one_swap(s1, s2))
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static boolean canBeEqualByOneSwap(String s1, String s2) {
        List<Integer> diffIndices = new ArrayList<>();
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                diffIndices.add(i);
                if (diffIndices.size() > 2) return false;
            }
        }
        return diffIndices.size() == 0 || (diffIndices.size() == 2 &&
                s1.charAt(diffIndices.get(0)) == s2.charAt(diffIndices.get(1)) &&
                s1.charAt(diffIndices.get(1)) == s2.charAt(diffIndices.get(0)));
    }

    public static void main(String[] args) {
        String s1 = "bank";
        String s2 = "kanb";
        System.out.println(canBeEqualByOneSwap(s1, s2));
    }
}
#include <iostream>
#include <vector>
#include <string>

bool canBeEqualByOneSwap(const std::string& s1, const std::string& s2) {
    std::vector<int> diffIndices;
    for (int i = 0; i < s1.length(); ++i) {
        if (s1[i] != s2[i]) {
            diffIndices.push_back(i);
            if (diffIndices.size() > 2) return false;
        }
    }
    return diffIndices.size() == 0 || (diffIndices.size() == 2 && s1[diffIndices[0]] == s2[diffIndices[1]] && s1[diffIndices[1]] == s2[diffIndices[0]]);
}

int main() {
    std::string s1 = "bank";
    std::string s2 = "kanb";
    std::cout << (canBeEqualByOneSwap(s1, s2) ? "true" : "false") << std::endl;
    return 0;
}
function canBeEqualByOneSwap(s1, s2) {
    const diffIndices = [];
    for (let i = 0; i < s1.length; i++) {
        if (s1[i] !== s2[i]) {
            diffIndices.push(i);
            if (diffIndices.length > 2) return false;
        }
    }
    return diffIndices.length === 0 || (diffIndices.length === 2 &&
           s1[diffIndices[0]] === s2[diffIndices[1]] &&
           s1[diffIndices[1]] === s2[diffIndices[0]]);
}

const s1 = "bank";
const s2 = "kanb";
console.log(canBeEqualByOneSwap(s1, s2));
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool canBeEqualByOneSwap(char* s1, char* s2) {
    int n = strlen(s1);
    int count = 0;
    int indices[2];
    for (int i = 0; i < n; i++) {
        if (s1[i] != s2[i]) {
            if (count < 2) indices[count] = i;
            count++;
        }
    }
    if (count == 0) return true;
    if (count != 2) return false;
    return s1[indices[0]] == s2[indices[1]] && s1[indices[1]] == s2[indices[0]];
}

int main() {
    char s1[] = "bank";
    char s2[] = "kanb";
    printf("%s", canBeEqualByOneSwap(s1, s2) ? "true" : "false");
    return 0;
}
using System;
using System.Collections.Generic;

class Program {
    static bool CanBeEqualByOneSwap(string s1, string s2) {
        List<int> diffIndices = new List<int>();
        for (int i = 0; i < s1.Length; i++) {
            if (s1[i] != s2[i]) {
                diffIndices.Add(i);
                if (diffIndices.Count > 2)
                    return false;
            }
        }
        return diffIndices.Count == 0 || (diffIndices.Count == 2 &&
                s1[diffIndices[0]] == s2[diffIndices[1]] &&
                s1[diffIndices[1]] == s2[diffIndices[0]]);
    }

    static void Main() {
        string s1 = "bank";
        string s2 = "kanb";
        Console.WriteLine(CanBeEqualByOneSwap(s1, s2));
    }
}

Python's list comprehension efficiently identifies mismatched indices, and then a simple conditional check confirms if a swap is feasible for equality.

Complexity

Time Complexity: O(n). Space Complexity: O(1) ignoring the input and output space as only a fixed number of indices are stored.

Try this approach in the editor

Approach 2: Permutation Check on Two Mismatches

Approach: If there are two mismatches in the strings, check if swapping these characters in one string equals two mismatched positions in the other string. Additionally, ensure they are permutations of each other since that validates the swap correctness for larger strings and edge cases.

from collections import Counter

def can_be_equal_by_one_swap(s1, s2):
    if Counter(s1) != Counter(s2):
        return False
    diff_indices = [i for i in range(len(s1)) if s1[i] != s2[i]]
    if len(diff_indices) == 0:
        return True
    if len(diff_indices) != 2:
        return False
    i, j = diff_indices
    return s1[i] == s2[j] and s1[j] == s2[i]

s1 = "bank"
s2 = "kanb"
print(can_be_equal_by_one_swap(s1, s2))
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static boolean arePermutations(String s1, String s2) {
        Map<Character, Integer> count = new HashMap<>();
        for (char ch : s1.toCharArray()) {
            count.put(ch, count.getOrDefault(ch, 0) + 1);
        }
        for (char ch : s2.toCharArray()) {
            count.put(ch, count.getOrDefault(ch, 0) - 1);
            if (count.get(ch) < 0) return false;
        }
        for (int value : count.values()) {
            if (value != 0) return false;
        }
        return true;
    }

    public static boolean canBeEqualByOneSwap(String s1, String s2) {
        if (!arePermutations(s1, s2)) return false;
        List<Integer> diffIndices = new ArrayList<>();
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                diffIndices.add(i);
                if (diffIndices.size() > 2) return false;
            }
        }
        return diffIndices.size() == 0 || (diffIndices.size() == 2 &&
                s1.charAt(diffIndices.get(0)) == s2.charAt(diffIndices.get(1)) &&
                s1.charAt(diffIndices.get(1)) == s2.charAt(diffIndices.get(0)));
    }

    public static void main(String[] args) {
        String s1 = "bank";
        String s2 = "kanb";
        System.out.println(canBeEqualByOneSwap(s1, s2));
    }
}
#include <iostream>
#include <unordered_map>
#include <string>

bool arePermutations(const std::string& s1, const std::string& s2) {
    std::unordered_map<char, int> count;
    for (auto ch : s1) count[ch]++;
    for (auto ch : s2) count[ch]--;
    for (auto pair : count) {
        if (pair.second != 0) return false;
    }
    return true;
}

bool canBeEqualByOneSwap(const std::string& s1, const std::string& s2) {
    if (!arePermutations(s1, s2)) return false;
    std::vector<int> diffIndices;
    for (int i = 0; i < s1.length(); ++i) {
        if (s1[i] != s2[i]) {
            diffIndices.push_back(i);
            if (diffIndices.size() > 2) return false;
        }
    }
    return diffIndices.size() == 0 || (diffIndices.size() == 2 && s1[diffIndices[0]] == s2[diffIndices[1]] && s1[diffIndices[1]] == s2[diffIndices[0]]);
}

int main() {
    std::string s1 = "bank";
    std::string s2 = "kanb";
    std::cout << (canBeEqualByOneSwap(s1, s2) ? "true" : "false") << std::endl;
    return 0;
}
function canBeEqualByOneSwap(s1, s2) {
    const createCharCount = (str) => {
        const count = {};
        for (const char of str) {
            count[char] = (count[char] || 0) + 1;
        }
        return count;
    };    
    const countS1 = createCharCount(s1);
    const countS2 = createCharCount(s2);

    for (const char in countS1) {
        if (countS1[char] !== countS2[char]) {
            return false;
        }
    }

    const diffIndices = [];
    for (let i = 0; i < s1.length; i++) {
        if (s1[i] !== s2[i]) {
            diffIndices.push(i);
            if (diffIndices.length > 2) return false;
        }
    }
    return diffIndices.length === 0 || (diffIndices.length === 2 &&
           s1[diffIndices[0]] === s2[diffIndices[1]] &&
           s1[diffIndices[1]] === s2[diffIndices[0]]);
}

const s1 = "bank";
const s2 = "kanb";
console.log(canBeEqualByOneSwap(s1, s2));
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>

bool arePermutations(char* s1, char* s2) {
    int count[256] = {0};
    for (int i = 0; s1[i] && s2[i]; i++) {
        count[s1[i]]++;
        count[s2[i]]--;
    }
    for (int i = 0; i < 256; i++) {
        if (count[i])
            return false;
    }
    return true;
}

bool canBeEqualByOneSwap(char* s1, char* s2) {
    int n = strlen(s1);
    if (!arePermutations(s1, s2)) return false;
    int count = 0;
    int indices[2];
    for (int i = 0; i < n; i++) {
        if (s1[i] != s2[i]) {
            if (count < 2) indices[count] = i;
            count++;
        }
    }
    if (count == 0) return true;
    if (count != 2) return false;
    return s1[indices[0]] == s2[indices[1]] && s1[indices[1]] == s2[indices[0]];
}

int main() {
    char s1[] = "bank";
    char s2[] = "kanb";
    printf("%s", canBeEqualByOneSwap(s1, s2) ? "true" : "false");
    return 0;
}
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
    static bool ArePermutations(string s1, string s2) {
        var count = new Dictionary<char, int>();
        foreach (char ch in s1) {
            if (count.ContainsKey(ch)){
                count[ch]++;
            } else {
                count[ch] = 1;
            }
        }
        foreach (char ch in s2) {
            if (!count.ContainsKey(ch) || count[ch] == 0) return false;
            count[ch]--;
        }
        return count.Values.All(v => v == 0);
    }

    static bool CanBeEqualByOneSwap(string s1, string s2) {
        if (!ArePermutations(s1, s2)) return false;
        List<int> diffIndices = new List<int>();
        for (int i = 0; i < s1.Length; i++) {
            if (s1[i] != s2[i]) {
                diffIndices.Add(i);
                if (diffIndices.Count > 2) return false;
            }
        }
        return diffIndices.Count == 0 || (diffIndices.Count == 2 &&
                s1[diffIndices[0]] == s2[diffIndices[1]] &&
                s1[diffIndices[1]] == s2[diffIndices[0]]);
    }

    static void Main() {
        string s1 = "bank";
        string s2 = "kanb";
        Console.WriteLine(CanBeEqualByOneSwap(s1, s2));
    }
}

This Python solution utilizes the Counter class to verify permutation status before proceeding to mismatch checks, reducing fragility for abnormal inputs.

Complexity

Time Complexity: O(n). Space Complexity: O(1) when considering only fixed-size storage.

Try this approach in the editor

Approach 3: Counting

We use a variable cnt to record the number of characters at the same position in the two strings that are different. If the two strings meet the requirements of the problem, then cnt must be 0 or 2. We also use two character variables c1 and c2 to record the characters that are different at the same position in the two strings.

While traversing the two strings simultaneously, for two characters a and b at the same position, if a \ne b, then cnt is incremented by 1. If at this time cnt is greater than 2, or cnt is 2 and a \ne c2 or b \ne c1, then we directly return false. Note to record c1 and c2.

At the end of the traversal, if cnt neq 1, return true.

The time complexity is O(n), where n is the length of the string. The space complexity is O(1).

function areAlmostEqual(s1: string, s2: string): boolean {
    let c1, c2;
    let cnt = 0;
    for (let i = 0; i < s1.length; ++i) {
        const a = s1.charAt(i);
        const b = s2.charAt(i);
        if (a != b) {
            if (++cnt > 2 || (cnt == 2 && (a != c2 || b != c1))) {
                return false;
            }
            c1 = a;
            c2 = b;
        }
    }
    return cnt != 1;
}
func areAlmostEqual(s1 string, s2 string) bool {
	cnt := 0
	var c1, c2 byte
	for i := range s1 {
		a, b := s1[i], s2[i]
		if a != b {
			cnt++
			if cnt > 2 || (cnt == 2 && (a != c2 || b != c1)) {
				return false
			}
			c1, c2 = a, b
		}
	}
	return cnt != 1
}
impl Solution {
    pub fn are_almost_equal(s1: String, s2: String) -> bool {
        if s1 == s2 {
            return true;
        }
        let (s1, s2) = (s1.as_bytes(), s2.as_bytes());
        let mut idxs = vec![];
        for i in 0..s1.len() {
            if s1[i] != s2[i] {
                idxs.push(i);
            }
        }
        if idxs.len() != 2 {
            return false;
        }
        s1[idxs[0]] == s2[idxs[1]] && s2[idxs[0]] == s1[idxs[1]]
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Counting Mismatches and Swapping

Time Complexity: O(n). Space Complexity: O(1) ignoring the input and output space as only a fixed number of indices are stored.

Permutation Check on Two Mismatches

Time Complexity: O(n). Space Complexity: O(1) when considering only fixed-size storage.

Counting–

Complexity analysis

ApproachTimeSpaceWhen to Use
Counting Mismatches and SwappingO(n)O(1)General case. Best approach for interviews and production due to simple logic.
Permutation Check on Two MismatchesO(n)O(1)Useful when framing the problem as validating a small permutation of mismatched characters.

Frequently asked questions

Is Check if One String Swap Can Make Strings Equal easy or hard?

Check if One String Swap Can Make Strings Equal is classified as an Easy problem on LeetCode with an acceptance rate around 49%. The challenge is recognizing that only two mismatches can be corrected by a single swap.

Check if One String Swap Can Make Strings Equal Python/Java solution

The typical Python or Java implementation iterates through both strings, records mismatched indices, and validates whether a swap fixes the mismatch. The code is usually under 10–15 lines and runs in O(n) time with O(1) space.

How to solve Check if One String Swap Can Make Strings Equal in O(n)?

Traverse both strings simultaneously and track indices where characters differ. If more than two mismatches appear, return false immediately. If exactly two mismatches exist, check whether swapping those characters would align the strings. This single pass ensures O(n) time and constant memory.

What is the best approach for Check if One String Swap Can Make Strings Equal?

The best approach is counting mismatches between the two strings in a single pass. If there are exactly two mismatched positions, verify that swapping those characters in one string makes them equal. If there are zero mismatches, the strings are already equal. This solution runs in O(n) time and O(1) space.

Is Check if One String Swap Can Make Strings Equal asked at Google/Amazon/Meta?

String comparison and swap-validation problems frequently appear in interviews at companies like Amazon, Google, and Meta. Variants often test your ability to reason about mismatches, permutations, or minimal edits between two strings.

What data structure is used in Check if One String Swap Can Make Strings Equal?

The optimal solution does not require complex data structures. A few integer variables or a small list to track mismatched indices is enough. Some variations describe the logic using hash table or counting ideas, but constant-space tracking is sufficient.

What is the time complexity of Check if One String Swap Can Make Strings Equal?

The optimal solution runs in O(n) time because you iterate through both strings once to find mismatches. Only two indices need to be stored, so the space complexity is O(1). This makes the algorithm efficient even for long strings.

Comments

Now write it yourselfClose this page and solve Check if One String Swap Can Make Strings Equal in the editor, without looking.
Practise Check if One String Swap Can Make Strings Equal