Python 1347.py
class Solution:
def minSteps(self, s: str, t: str) -> int:
freqS = defaultdict(int)
for c in s:
freqS[c] += 1
freqT = defaultdict(int)
for c in t:
freqT[c] += 1
result = 0
for f in freqS:
if freqS[f] > freqT[f]:
result += freqS[f] - freqT[f]
return result
Difficulty
and has an acceptance rate of about 83% (400k+ 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 that computes the minimum number of character deletions required to transform one string into another by ensuring that the first string does not contain any character in excess of its count in the second string. The algorithm proceeds by building frequency maps for both input strings, comparing the counts, and accumulating the surplus characters from the first string.
Key Steps
The first phase constructs a frequency dictionary for the source string. A defaultdict with integer default values is employed so that each new character key starts at zero, allowing direct increment without prior existence checks.
freqS = defaultdict(int)
for c in s:
freqS[c] += 1
The second phase mirrors the first, building a frequency dictionary for the target string.
freqT = defaultdict(int)
for c in t:
freqT[c] += 1
The third phase iterates over the keys of the source frequency map. For each character, it checks whether the count in the source exceeds the count in the target. When this condition holds, the difference is added to the running total, representing the number of deletions needed for that character.
result = 0
for f in freqS:
if freqS[f] > freqT[f]:
result += freqS[f] - freqT[f]
Finally, the accumulated result is returned.
return result
Edge Cases Handled
When either input string is empty, the corresponding frequency dictionary remains empty. The iteration over freqS naturally yields zero contributions to the result because there are no characters to compare, leading to a correct return value of zero deletions when both strings are empty or when only the target string is empty.
If a character appears exclusively in the source string and not in the target string, the lookup freqT[f] returns the default integer value zero. The condition freqS[f] > freqT[f] evaluates to true, and the entire count of that character is added to the result, correctly accounting for the need to delete all occurrences of that character.
Conversely, characters that exist only in the target string are never visited in the final loop because the iteration is limited to keys present in freqS. This design implicitly treats such characters as having no impact on the deletion count, which aligns with the problem’s requirement to only reduce excess characters from the source string.
When both strings contain the same multiset of characters, each comparison yields equality, the conditional block is skipped, and the result remains zero, indicating that no deletions are necessary.
Performance Optimizations
The algorithm leverages defaultdict to avoid explicit existence checks during frequency accumulation, enabling constant-time updates for each character. By constructing the two frequency maps in separate linear passes, the code ensures that each character of the input strings is processed exactly once, minimizing redundant work.
The final aggregation step iterates only over the distinct characters present in the source string, rather than over the entire possible character set. This reduces the number of iterations when the input strings contain a limited alphabet, providing a practical speed advantage.
All operations-dictionary lookups, increments, and arithmetic-are performed in constant time, allowing the overall routine to scale linearly with the combined length of the input strings while maintaining a low constant factor due to the straightforward loop structures.
ELI5 - Simplified Explanation
Imagine you have two boxes filled with colorful letter blocks. The goal is to see how many letters need to be swapped or changed so that both boxes have the exact same collection of letters.
First, the code looks at the first box and counts how many times each specific letter appears, keeping a tally on a notepad. Then, it does the exact same thing for the second box, creating a second tally of all those letters.
Once both lists are ready, it compares the two. It looks at each letter type and asks if the first box has more of that letter than the second box. If the first box has extra copies of a letter, it counts exactly how many extras there are and adds that number to a little pile. By the time it finishes checking every letter, that pile holds the total number of changes required to make the two boxes match.
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 | JS | Java | Go | TS | ||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| martianoff | Scala | |||||||||
| muhammadfarhankt | Go | |||||||||
| pruthvikp | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| martianoff | Scala | |||||||||
| muhammadfarhankt | Go | |||||||||
| pruthvikp | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 1657: Determine if Two Strings Are Close
- problem 2186: Minimum Number of Steps to Make Two Strings Anagram II
Solved On The Same Day
- problem 880: Decoded String at Index
- problem 912: Sort an Array
- problem 923: 3Sum With Multiplicity
- problem 973: K Closest Points to Origin
- problem 1010: Pairs of Songs With Total Durations Divisible by 60
- problem 1054: Distant Barcodes
- problem 1079: Letter Tile Possibilities
- problem 1090: Largest Values From Labels
- problem 1366: Rank Teams by Votes
- problem 1419: Minimum Number of Frogs Croaking
- problem 1738: Find Kth Largest XOR Coordinate Value
- problem 1814: Count Nice Pairs in an Array
- problem 1985: Find the Kth Largest Integer in the Array
- problem 2018: Check if Word Can Be Placed In Crossword
- problem 2150: Find All Lonely Numbers in the Array
- problem 2182: Construct String With Repeat Limit
- problem 2225: Find Players With Zero or One Losses
- problem 2232: Minimize Result by Adding Parentheses to Expression
- problem 2244: Minimum Rounds to Complete All Tasks
- problem 2284: Sender With Largest Word Count
- problem 2343: Query Kth Smallest Trimmed Number
- problem 2526: Find Consecutive Integers from a Data Stream
- problem 2844: Minimum Operations to Make a Special Number
- problem 2860: Happy Students
- problem 906: Super Palindromes
- problem 992: Subarrays with K Different Integers
- problem 1106: Parsing A Boolean Expression
- problem 1601: Maximum Number of Achievable Transfer Requests
- problem 2081: Sum of k-Mirror Numbers
- problem 2122: Recover the Original Array
- problem 2416: Sum of Prefix Scores of Strings
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