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]]
Difficulty
and has an acceptance rate of about 50% (600k+ submissions).
Typical patterns to solve this problem:
- Counting
- Hash Table
- String
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 859: Buddy Strings
- problem 2531: Make Number of Distinct Characters Equal
Solved On The Same Day
- problem 1317: Convert Integer to the Sum of Two No-Zero Integers
- problem 1417: Reformat The String
- problem 1556: Thousand Separator
- problem 2259: Remove Digit From Number to Maximize Result
- problem 2582: Pass the Pillow
- problem 2605: Form Smallest Number From Two Digit Arrays
- problem 2729: Check if The Number is Fascinating
- problem 881: Boats to Save People
- problem 1503: Last Moment Before All Ants Fall Out of a Plank
- problem 1578: Minimum Time to Make Rope Colorful
- problem 1685: Sum of Absolute Differences in a Sorted Array
- problem 1701: Average Waiting Time
Extra
- 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