Problem 1790

Abstract / Summary

Check if swapping two characters in one string can make it the same as another string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1790.py

class Solution:
    def areAlmostEqual(self, s1: str, s2: str) -> bool:
        diffs = []
        for i, (c1, c2) in enumerate(zip(s1, s2)):
            if c1 != c2:
                diffs.append(i)

        # exactly two or no differences
        if not diffs:
            return True
        if len(diffs) != 2:
            return False

        # make sure the swapped letters are identical
        return s1[diffs[0]] == s2[diffs[1]] and s1[diffs[1]] == s2[diffs[0]]
15 lines | 486 bytes | submitted November 3, 2023 | GitHub   18% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (600k+ submissions).

Typical patterns to solve this problem:
  • Counting
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method areAlmostEqual that determines whether two strings of equal length can be made identical by swapping at most one pair of characters in the first string. The algorithm proceeds by scanning both strings in parallel, collecting the indices where the characters differ, and then applying a small set of logical checks to decide the result.

Key Steps

The first logical block iterates over the characters of s1 and s2 simultaneously. For each position, the code compares the characters and records the index when a mismatch occurs.

diffs = []
for i, (c1, c2) in enumerate(zip(s1, s2)):
    if c1 != c2:
        diffs.append(i)

After the scan, the method evaluates the size of the diffs list. If the list is empty, the strings are already identical and the method returns True.

if not diffs:
    return True

If the number of mismatched positions is anything other than two, a single swap cannot resolve the differences, so the method returns False.

if len(diffs) != 2:
    return False

When exactly two mismatches are present, the code verifies that swapping the characters at those two indices would align the strings. This is done by checking that the character from s1 at the first mismatched index equals the character from s2 at the second mismatched index, and vice-versa.

return s1[diffs[0]] == s2[diffs[1]] and s1[diffs[1]] == s2[diffs[0]]

Edge Cases Handled

The algorithm gracefully handles the situation where the input strings are already equal; the early if not diffs clause captures this and returns True without further processing. It also correctly rejects cases where the number of differing positions is one, three, or any number greater than two, because a single swap cannot reconcile more than two mismatches. When exactly two mismatches exist, the final comparison ensures that the characters are cross-compatible for a swap, thereby covering cases where the mismatched characters are identical (e.g., swapping two identical letters) as well as cases where they differ but can be exchanged to achieve equality.

Performance Optimizations

The implementation performs a single linear pass over the input strings, collecting only the indices of mismatches. By stopping the collection after the entire strings are examined, it avoids unnecessary early termination logic while still keeping the amount of stored data minimal-at most two indices are needed for the final decision. The use of zip together with enumerate provides an efficient iterator that yields paired characters without creating intermediate lists. The final conditional check operates directly on the original strings using the stored indices, eliminating the need for any additional data structures or string reconstruction. This streamlined approach ensures that the method runs with minimal overhead while maintaining clear and direct logic.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have two rows of colorful building blocks and you want to see if they look almost exactly the same. The code starts by looking at both rows side by side, one block at a time. It keeps a little list of all the spots where the blocks do not match. If every block matches perfectly, then the rows are already the same. If the list of mismatched spots has exactly two items, the code checks if those two blocks were just swapped with each other. If the first mismatched block in the first row is the same as the second mismatched block in the second row, and the other way around, then swapping them once would make the two rows identical.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.11 | σ = 1.55

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
Shamik07 Dart
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
Shamik07 Dart
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
30 links | 17 authors | 11 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

13 solutions   November 3, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality