Minimum Number of Steps to Make Two Strings Anagram (LeetCode 1347): Solution and Explanation
Given two equal-length strings s and t, find the fewest single-character replacements in t that turn it into an anagram of s.
Intuition
An anagram only cares about how many of each letter a string holds, never their order. So the positions of the letters are irrelevant and the whole problem lives in 26 counters.
Put both strings on one balance: every letter of s adds 1 to its bucket and every letter of t subtracts 1. A bucket that ends at 0 is perfectly matched. A positive bucket counts letters that s has and t lacks; a negative bucket counts letters in t that have no partner.
One replacement takes one surplus letter from a negative bucket and turns it into a missing letter from a positive bucket, fixing one unit on each side. Since the strings have the same length, the positives and negatives sum to the same total, and that total is the answer.
Approach: Single balance array
- Create an array
countof 26 zeros. - For each character of
s, increment its bucket. - For each character of
t, decrement its bucket. - Add up the buckets that are positive and return the sum.
Step-by-step example
s = "bab", t = "aba"
- Counting
sgivesb = 2,a = 1. - Counting
tsubtractsatwice andbonce, leavinga = -1andb = +1. - Bucket
bis +1:shas one morebthant, so one letter oftmust becomeb. - Bucket
ais -1: that is the extraaintthat gets rewritten. - The positive buckets sum to 1, so the answer is
1(for exampleababecomesbba).
Code: Python, Java, C++
1class Solution:
2 def minSteps(self, s: str, t: str) -> int:
3 count = [0] * 26
4 for ch in s:
5 count[ord(ch) - ord('a')] += 1
6 for ch in t:
7 count[ord(ch) - ord('a')] -= 1
8 steps = 0
9 for c in count:
10 if c > 0:
11 steps += c
12 return steps1class Solution {
2 public int minSteps(String s, String t) {
3 int[] count = new int[26];
4 for (char ch : s.toCharArray()) {
5 count[ch - 'a']++;
6 }
7 for (char ch : t.toCharArray()) {
8 count[ch - 'a']--;
9 }
10 int steps = 0;
11 for (int c : count) {
12 if (c > 0) {
13 steps += c;
14 }
15 }
16 return steps;
17 }
18}1class Solution {
2public:
3 int minSteps(string s, string t) {
4 int count[26] = {0};
5 for (char ch : s) {
6 count[ch - 'a']++;
7 }
8 for (char ch : t) {
9 count[ch - 'a']--;
10 }
11 int steps = 0;
12 for (int c : count) {
13 if (c > 0) {
14 steps += c;
15 }
16 }
17 return steps;
18 }
19};Time and space complexity
O(n)
Each string is read once, and the final sum looks at 26 buckets.
O(1)
The balance array always has 26 entries, no matter how long the strings are.
Other approaches
Two separate counters (time O(n), space O(1))
Count s and t into two arrays or hash maps, then sum max(0, countS[c] - countT[c]) over all letters. Same result, slightly more memory and code.
Sort both strings (time O(n log n), space O(n))
Sort s and t, then walk them with two pointers counting matched letters; the answer is n - matched. It works but sorting costs O(n log n).
Common mistakes
- Summing absolute values of all buckets. That counts each replacement twice, once for the letter removed and once for the letter added, so you must divide by 2 or sum only one sign.
- Comparing the strings position by position. Order does not matter for an anagram, so
abandbaneed 0 steps even though every position differs. - Using a hash map when 26 fixed buckets do the job. It is not wrong, but the array is simpler and faster.
Frequently asked questions
Why is summing only the positive buckets enough?
Both strings have the same length, so the total of all buckets is 0. The positive part and the negative part therefore have the same size, and each replacement fixes one unit of each.
Could I sum the negative buckets instead?
Yes. The sum of the absolute values of the negative buckets is the same number, because the two parts must cancel.
What if the strings had different lengths?
The problem guarantees equal lengths. With different lengths a replacement alone could never make them anagrams, because replacements do not change length.
What is the time and space complexity?
O(n) time to read both strings once and O(1) extra space for 26 counters.