Fewest Letter Swaps to Rearrange One Word Into Another's Letters
StringsAuto-graded · 22 test casesLast updated
Count letter frequencies in two equal-length strings to find the fewest in-place letter replacements that make the second string an anagram of the first.
You are given a target word source and a second word target of exactly the same length. Both contain only lowercase English letters.
You may edit target by choosing one position and overwriting the letter there with any lowercase letter. Each such overwrite counts as one operation. Your goal is to make target an anagram of source, that is, both words must end up with the same letters occurring the same number of times, regardless of order.
Return the smallest number of overwrite operations required.
Rules
- Only
targetcan be modified.sourceis never changed. - An operation overwrites exactly one letter. You cannot add or remove letters, so the length of
targetstays the same. - Letter order is irrelevant for anagrams, so rearranging letters costs nothing.
- If
targetis already an anagram ofsource, the answer is0.
Constraints
1 <= len(source) == len(target) <= 5 * 10^4sourceandtargetcontain only the lowercase lettersatoz.- The answer never exceeds
len(target), so it fits in a 32-bit signed integer.
Examples
Example 1
Input: min_overwrites_for_anagram('abc', 'bbd')
Output: 2
Example 2
Input: min_overwrites_for_anagram('night', 'thing')
Output: 0
Example 3
Input: min_overwrites_for_anagram('aabbcc', 'abcdef')
Output: 3
Hints
Hint 1
Anagrams care only about how many times each letter appears, not where. Reduce each string to a table of letter counts.
Hint 2
For each letter, compare its count in source with its count in target. A letter where target has fewer copies than source is one that must be created by overwriting.
Hint 3
Sum the shortages max(0, count_in_source - count_in_target) over all letters. Because the lengths are equal, total shortage equals total surplus, so each shortage can be paired with one surplus character to overwrite.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Whether two strings are anagrams depends only on their letter counts. So we build a frequency table for source and one for target.
For each letter c:
- If
sourcehas more copies ofcthantarget, thentargetis short byneed[c] - have[c]copies. Each missing copy must be produced by one overwrite. - Otherwise
targetalready has enough ofcand this letter needs nothing.
The answer is the total shortage over all letters:
answer = sum over c of max(0, need[c] - have[c])
Why it is correct
Lower bound. One overwrite increases the count of exactly one letter by one, so it can reduce the total shortage by at most 1. If the total shortage is D, at least D operations are needed.
Upper bound. Both strings have the same length, so the sum of all differences need[c] - have[c] is zero. Hence the total shortage equals the total surplus, which is D. That means target contains exactly D surplus characters (extra copies of over-represented letters, or letters absent from source). Overwrite each of them with a letter that is currently short. Every such step removes one surplus and fills one shortage, so after D steps all counts match.
Lower and upper bounds coincide, so D is the minimum.
The max(0, ...) clamp matters: without it, surpluses would cancel shortages and the sum would always be zero.
Complexity
- Time: O(n) to build the two counters, plus at most 26 steps for the sum.
- Space: O(1), since each counter holds at most 26 keys.
Reference solution
from collections import Counter
def min_overwrites_for_anagram(source: str, target: str) -> int:
need = Counter(source)
have = Counter(target)
return sum(max(0, need[c] - have[c]) for c in need)