Minimum Number of Steps to Make Two Strings Anagram (LeetCode 1347): Solution and Explanation

Medium
Hash Table
String
Counting

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

  1. Create an array count of 26 zeros.
  2. For each character of s, increment its bucket.
  3. For each character of t, decrement its bucket.
  4. Add up the buckets that are positive and return the sum.

Step-by-step example

s = "bab", t = "aba"
  1. Counting s gives b = 2, a = 1.
  2. Counting t subtracts a twice and b once, leaving a = -1 and b = +1.
  3. Bucket b is +1: s has one more b than t, so one letter of t must become b.
  4. Bucket a is -1: that is the extra a in t that gets rewritten.
  5. The positive buckets sum to 1, so the answer is 1 (for example aba becomes bba).

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 steps
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Single balance array O(n)
Two separate counters O(n)
Sort both strings O(n log n)
Time

O(n)

Each string is read once, and the final sum looks at 26 buckets.

Space

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 ab and ba need 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.