Minimum Number of Steps to Make Two Strings Anagram
Medium
Topics
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
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.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
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
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
- Count the letters of
sand the letters oft. - For each of the 26 letters, take
max(0, count_s - count_t). - Sum those shortfalls and return the total.
- Equivalently: build one table, adding for
sand subtracting fort, 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 1Complexity
- 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
srather thant. The counts make it symmetric here, but the statement only permits changingt.
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)import java.util.*;
class Solution {
public int minSteps(String s, String t) {
int[] need = new int[26];
for (int i = 0; i < s.length(); i++) need[s.charAt(i) - 'a']++;
for (int i = 0; i < t.length(); i++) need[t.charAt(i) - 'a']--;
int total = 0;
for (int v : need) if (v > 0) total += v;
return total;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int minSteps(string s, string t) {
vector<int> need(26, 0);
for (char ch : s) need[ch - 'a']++;
for (char ch : t) need[ch - 'a']--;
int total = 0;
for (int v : need) if (v > 0) total += v;
return total;
}
};/**
* @param {string} s
* @param {string} t
* @return {number}
*/ var minSteps = function(s, t) {
const need = new Array(26).fill(0);
const base = 97;
for (const ch of s) need[ch.charCodeAt(0) - base]++;
for (const ch of t) need[ch.charCodeAt(0) - base]--;
let total = 0;
for (const v of need) if (v > 0) total += v;
return total;
};