EasyNo. 1790

Check if One String Swap Can Make Strings Equal — LeetCode 1790 Python Solution

Pattern
Hash Map
Topics
Hash Table, String, Counting
Reading time
2 min

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.

Example

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

Python solution

PythonSolution
class Solution:
    def areAlmostEqual(self, s1: str, s2: str) -> bool:
        cnt = 0
        c1 = c2 = None
        for a, b in zip(s1, s2):
            if a != b:
                cnt += 1
                if cnt > 2 or (cnt == 2 and (a != c2 or b != c1)):
                    return False
                c1, c2 = a, b
        return cnt != 1

Complexity

Time
O(n)where n is the length of the string
Space · auxiliary
O(1)

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1790. Check if One String Swap Can Make Strings Equal is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
1781Sum of Beauty of All SubstringsMedium
0299Bulls and CowsMedium
0383Ransom NoteEasy
0387First Unique Character in a StringEasy
0451Sort Characters By FrequencyMedium
0692Top K Frequent WordsMedium

Frequently asked questions

How hard is LeetCode 1790. Check if One String Swap Can Make Strings Equal?

LeetCode 1790. Check if One String Swap Can Make Strings Equal is rated Easy on LeetCode.

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

The Python solution on this page runs in O(n), where n is the length of the string.

What is the space complexity of LeetCode 1790. Check if One String Swap Can Make Strings Equal?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 1790. Check if One String Swap Can Make Strings Equal cover?

LeetCode 1790. Check if One String Swap Can Make Strings Equal is tagged Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.