Minimum Number of Steps to Make Two Strings Anagram

Medium

Topics
StringHash TableCounting

s and t have the same length. In one step you may replace any character of t with any other letter.

Return the fewest steps needed to make t an anagram of s.

Example 1

0a1201b211letterin sin tshort
a letter t is short ofno shortfall
Turning aba into an anagram of bab takes 1 step. Only the letter counts matter, never the positions, so the table is the whole problem: the last column is how many of each letter t is missing. Those shortfalls add to 1 and the surplus adds to 1 — equal, because the lengths are, and each step spends one surplus character on one shortfall, so counting both sides would double the answer.
Only t may be changed, and a replacement never alters its length.
Input:  s = "bab", t = "aba"
Output: 1
Explanation: Replace one "a" in t with "b", giving t two bs and one a to match s.

Example 2

0a0101c1202d1013e3124i0105l1016o1017p0108r0109t110letterin sin tshort
a letter t is short ofno shortfall
Input:  s = "leetcode", t = "practice"
Output: 5
Explanation: Only c, t and one e are useful; the other five characters of t have to be replaced.

Example 3

0a3301g1102m1103n1104r110letterin sin tshort
no shortfall
Input:  s = "anagram", t = "mangaar"
Output: 0
Explanation: Already an anagram, so no step is needed.

Constraints

  • 1 <= s.length <= 5 * 10^4
  • s.length == t.length
  • s and t consist of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls

Intuition

Because the lengths are equal and a replacement does not change the length, the only thing that matters is the letter counts. Position is irrelevant, so this is not about aligning the strings at all.

Compare the two count tables. Where s needs more of a letter than t has, that shortfall must be filled, and each unit costs one step. The answer is the total shortfall over all 26 letters.

There is no need to count the surplus separately, and this is the part worth being sure about: since the lengths are equal, the total surplus equals the total shortfall. Each replacement removes one surplus character and supplies one missing one, so one step closes one unit of shortfall — adding both would double the answer.

A single-table variant is tidier still: increment on the letters of s and decrement on the letters of t, then sum the positive entries.

Approach

  1. Count the letters of s and the letters of t.
  2. For each of the 26 letters, take max(0, count_s - count_t).
  3. Sum those shortfalls and return the total.
  4. Equivalently: build one table, adding for s and subtracting for t, and sum the entries that are positive.

Walkthrough

s = "leetcode", t = "practice"

counts
           s        t      shortfall for s
   a       0        1          0
   c       1        2          0
   d       1        0          1
   e       3        1          2
   i       0        1          0
   l       1        0          1
   o       1        0          1
   p       0        1          0
   r       0        1          0
   t       1        1          0

shortfall total 1 + 2 + 1 + 1 = 5

answer 5

checking against the surplus
   t has surplus: a 1, c 1, i 1, p 1, r 1  = 5
   equal to the shortfall, as it must be when the lengths
   match. Adding both would give 10, which is twice the
   real answer.

s = "bab", t = "aba"
   s: a 1, b 2      t: a 2, b 1
   shortfall for s: b by 1
   answer 1

Complexity

  • Time — O(n): one pass over each string and a fixed 26-entry sum.
  • Space — O(1): one table of 26 counts, whatever the input length.

Common Pitfalls

  • Adding the surplus as well as the shortfall, which doubles the answer.
  • Comparing the strings position by position. The target is an anagram, so order does not matter.
  • Summing the absolute differences, which is the same mistake as counting both sides.
  • Assuming the lengths might differ. They do not, which is what makes shortfall and surplus equal.
  • Replacing characters in s rather than t. The counts make it symmetric here, but the statement only permits changing t.

Full Solution — all languages

class Solution:
    def minSteps(self, s, t):
        # Position is irrelevant; only the letter counts matter.
        need = [0] * 26
        base = ord("a")

        for ch in s:
            need[ord(ch) - base] += 1
        for ch in t:
            need[ord(ch) - base] -= 1

        # Only the shortfalls. The surplus equals it, since the lengths
        # match, so counting both would double the answer.
        return sum(v for v in need if v > 0)
SensAI
Beta
Tap the mic to stop voice mode