KatInterview

Fewest Letter Swaps to Rearrange One Word Into Another's Letters

StringsAuto-graded · 22 test cases
MediumAuto-gradedStringsstringshash-mapfrequency-counting

Last 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 target can be modified. source is never changed.
  • An operation overwrites exactly one letter. You cannot add or remove letters, so the length of target stays the same.
  • Letter order is irrelevant for anagrams, so rearranging letters costs nothing.
  • If target is already an anagram of source, the answer is 0.

Constraints

  • 1 <= len(source) == len(target) <= 5 * 10^4
  • source and target contain only the lowercase letters a to z.
  • 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.