Problem 1347

Abstract / Summary

Make two strings have the same character counts by changing characters with the fewest total changes.

Note

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

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
16 lines | 387 bytes | submitted September 28, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 83% (400k+ 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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.08 | σ = 1.30

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 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
33 links | 21 authors | 9 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

32 solutions   September 28, 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