Python 1657.py
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
if len(word1) != len(word2):
return False
def getHistogram(w):
freq = defaultdict(int)
for c in w:
freq[c] += 1
return freq
f1 = getHistogram(word1)
f2 = getHistogram(word2)
return f1.keys() == f2.keys() and sorted(f1.values()) == sorted(f2.values())
Difficulty
and has an acceptance rate of about 54% (1+ million submissions).
Typical patterns to solve this problem:
- Counting
- Hash Table
- Sorting
- 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 class Solution with a method closeStrings that determines whether two input strings can be transformed into each other using a specific set of operations. The method first checks a basic length condition, then builds frequency histograms for each string, and finally compares the character sets and the multiset of frequencies. The logic is concise and leverages Python’s built-in data structures to achieve the required checks efficiently.
Key Steps
Length Check
The very first operation verifies that the two strings have identical lengths. If the lengths differ, the method returns False immediately, avoiding any further processing.
if len(word1) != len(word2):
return False
This early exit prevents unnecessary work when the strings cannot possibly be transformed into each other because the total number of characters is different.
Histogram Construction
A nested helper function getHistogram creates a frequency map for a given string. It uses defaultdict(int) to simplify the counting logic, incrementing the count for each character encountered.
def getHistogram(w):
freq = defaultdict(int)
for c in w:
freq[c] += 1
return freq
The function is called separately for word1 and word2, producing two dictionaries f1 and f2 that map characters to their occurrence counts.
f1 = getHistogram(word1)
f2 = getHistogram(word2)
Set and Frequency Comparison
The final return statement performs two logical checks:
-
It compares the sets of keys (the distinct characters) from both histograms. Equality of these sets ensures that both strings contain exactly the same characters, regardless of order or frequency.
-
It compares the sorted lists of frequency values from both histograms. Sorting the frequency values and then checking equality verifies that the multiset of counts matches, which is necessary for the transformation rules to be satisfied.
return f1.keys() == f2.keys() and sorted(f1.values()) == sorted(f2.values())
Both conditions must hold for the method to return True.
Edge Cases Handled
The code gracefully handles several edge conditions without additional branching:
-
Empty strings: When both inputs are empty, the length check passes, the histograms are empty, and the key sets as well as the sorted frequency lists are equal, resulting in
True. If only one string is empty, the length mismatch triggers an earlyFalse. -
Strings with identical characters but different frequencies: The key set comparison succeeds, but the sorted frequency lists differ, leading to a
Falseresult. This correctly reflects the inability to transform when the distribution of character counts cannot be matched. -
Strings with the same frequency distribution but different characters: The frequency lists may match after sorting, but the key set comparison fails, causing the method to return
False. This captures the requirement that the exact character set must be shared. -
Strings containing repeated characters: The histogram correctly aggregates counts, and the sorted frequency comparison accounts for any number of repetitions, ensuring accurate evaluation.
Performance Optimizations
The implementation incorporates several choices that contribute to efficient execution:
-
Early termination on length mismatch eliminates the need for histogram construction when the strings cannot possibly be transformed, saving both time and memory.
-
Use of
defaultdict(int)avoids explicit existence checks for each character during counting, reducing overhead in the inner loop. -
Direct comparison of dictionary key views (
f1.keys() == f2.keys()) leverages the fact that dictionary key views support set-like equality checks, providing a fast way to verify that the character sets match. -
Sorting of frequency values is performed only once per string, and the resulting lists are compared directly. Since the number of distinct characters is bounded by the alphabet size (at most 26 for lowercase English letters), the sorting step operates on a small collection, keeping the overall cost low.
-
Avoidance of intermediate data structures beyond the necessary histograms and sorted lists keeps memory usage modest, especially for long input strings where the number of distinct characters remains limited.
ELI5 - Simplified Explanation
Imagine two boxes filled with colorful building blocks. The goal of this code is to check if these two boxes are essentially the same. First, the code counts how many blocks are in each box. If the boxes have a different number of blocks, they cannot be the same, so the answer is no. If they have the same number, the code starts looking closer. It makes a little list for each box to keep track of how many blocks of each color are inside. Once all the blocks are counted, the code compares the two lists. It checks that both boxes have the exact same set of colors. Then, it sorts the numbers of blocks from smallest to largest to see if the pattern of how many blocks there are of each color matches up perfectly. If the colors and the tallies line up, these two boxes are considered a match.
Code Quality
Complexity Analysis
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 | Go | Rust | TS | ||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| muhammadfarhankt | Go | |||||||||
| pruthvikp | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| yuanliu666 | Kotlin | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| muhammadfarhankt | Go | |||||||||
| pruthvikp | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| yuanliu666 | Kotlin | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 859: Buddy Strings
- problem 1247: Minimum Swaps to Make Strings Equal
- problem 1347: Minimum Number of Steps to Make Two Strings Anagram
Solved On The Same Day
- problem 724: Find Pivot Index
- problem 872: Leaf-Similar Trees
- problem 933: Number of Recent Calls
- problem 1207: Unique Number of Occurrences
- problem 1732: Find the Highest Altitude
- problem 2215: Find the Difference of Two Arrays
- problem 328: Odd Even Linked List
- problem 443: String Compression
- problem 649: Dota2 Senate
- problem 735: Asteroid Collision
- problem 875: Koko Eating Bananas
- problem 901: Online Stock Span
- problem 1161: Maximum Level Sum of a Binary Tree
- problem 1268: Search Suggestions System
- problem 1282: Group the People Given the Group Size They Belong To
- problem 1372: Longest ZigZag Path in a Binary Tree
- problem 1448: Count Good Nodes in Binary Tree
- problem 1456: Maximum Number of Vowels in a Substring of Given Length
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 1647: Minimum Deletions to Make Character Frequencies Unique
- problem 1926: Nearest Exit from Entrance in Maze
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
- problem 2352: Equal Row and Column Pairs
- problem 2390: Removing Stars From a String
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