JJobsMoi
SoFi
SO

Minimum Number of Steps to Make Two Strings Anagram

Codingmedium

Problem

You are given two strings, source and target, both consisting only of lowercase English letters and both of the same length.

In a single step, you may pick any one character in source and replace it with any other lowercase letter you like. Your goal is to make source an anagram of target (that is, after all replacements, source and target contain exactly the same multiset of letters, though not necessarily in the same order).

Return the minimum number of single-character replacement steps needed to accomplish this.

Notes to keep in mind:

  • source and target always have equal length, so you never need to insert or delete characters — only replace them.
  • Characters that already appear the correct number of times in both strings should be left untouched; only the "excess" characters in source (relative to what target needs) must be changed.

Examples

Example 1:

Input: source = "aabcc", target = "abccc"

Output: 1

Explanation:

source has letter counts {a:2, b:1, c:2} while target has {a:1, b:1, c:3}. source has one extra a and is missing one c, so changing that single extra a into a c makes the two strings anagrams of each other.

Example 2:

Input: source = "xyz", target = "xyz"

Output: 0

Explanation:

The two strings already have identical letter counts, so no replacements are required.

Example 3:

Input: source = "aaaa", target = "bbbb"

Output: 4

Explanation:

None of the letters overlap between the two strings, so every character in source must be replaced to match the required counts in target.

Constraints

  • 1 <= source.length == target.length <= 5 * 10^4
  • source and target consist only of lowercase English letters.

Solution

Loading editor…

Sign in to get AI feedback on your answer. Your work is saved while you do.

Sign in to evaluate