Minimum Number of Steps to Make Two Strings Anagram

Medium Arrays & Hashing Hashing Original on LeetCode

Minimum Number of Steps to Make Two Strings Anagram is a medium arrays & hashing problem solved with the hashing pattern. The best approach, optimal (letter counts), runs in O(n) time and O(1) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (match letters one by one) up.

Problem

You are given two strings s and t of the same length, made of lowercase English letters. In one step you may pick any position in t and replace its letter with any other letter.

Return the minimum number of steps needed to make t an anagram of s, meaning t uses exactly the same letters as s, each the same number of times, in any order.

Examples

Example 1

Input
s = "listen", t = "tinsel"
Output
0
Why
Both words already use exactly the same letters.

Example 2

Input
s = "banana", t = "bandit"
Output
3
Why
s needs two more 'a's and one more 'n' than t has; turning 'd', 'i', 't' into 'a', 'a', 'n' takes 3 replacements.

Constraints

  • 1 <= s.length <= 5 * 10^4
  • s.length == t.length
  • s and t contain only lowercase English letters.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (match letters one by one)O(n²)O(n)
Optimal (letter counts)O(n)O(1)

1Brute force (match letters one by one)

TimeO(n²)Each of the n letters of s may scan all of t.
SpaceO(n)The used-flags array for t.

For each letter of s, look for an unused equal letter in t and mark it as used. Every letter of s that finds no partner needs one replacement in t.

  1. used = boolean array over t, steps = 0.
  2. For each character c of s, scan t for an index j with t[j] == c and not used[j].
  3. If found, mark used[j]; otherwise steps++.
  4. Return steps.
class Solution {
    public int minSteps(String s, String t) {
        int n = t.length(), steps = 0;
        boolean[] used = new boolean[n];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            boolean found = false;
            for (int j = 0; j < n; j++) {
                if (!used[j] && t.charAt(j) == c) {
                    used[j] = true;
                    found = true;
                    break;
                }
            }
            if (!found) steps++;
        }
        return steps;
    }
}

2Optimal (letter counts)

TimeO(n)One pass over both strings plus 26 counters.
SpaceO(1)A fixed array of 26 integers.

Only how many of each letter matters. Add 1 for every letter of s and subtract 1 for every letter of t in one array of 26 counters. A positive counter means s has that many copies that t lacks, and each lacking copy costs exactly one replacement. Because the lengths are equal, the surplus letters of t are exactly enough to be turned into them.

  1. count[26] = 0. For each i: count[s[i] - 'a']++, count[t[i] - 'a']--.
  2. Return the sum of the positive counters.
class Solution {
    public int minSteps(String s, String t) {
        int[] count = new int[26];
        for (int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - 'a']++;
            count[t.charAt(i) - 'a']--;
        }
        int steps = 0;
        for (int c : count) {
            if (c > 0) steps += c;
        }
        return steps;
    }
}

Edge cases to test

  • The strings are already anagrams (answer 0)
  • No letters in common (answer n)
  • Repeated letters, where only some copies are matched
  • Single-character strings

Hints

Hint 1

Letters of t that can be paired with an equal letter of s never need to change.

Hint 2

Count each letter in s and in t. For a letter that appears more often in s, the missing copies must be created by replacing something in t.

Hint 3

The answer is the sum over all letters of max(0, countS[c] - countT[c]).

FAQ

What is the best time complexity for Minimum Number of Steps to Make Two Strings Anagram?

Optimal (letter counts) runs in O(n) time and O(1) extra space. One pass over both strings plus 26 counters.

Which pattern does Minimum Number of Steps to Make Two Strings Anagram use?

It is a arrays & hashing problem that uses the hashing pattern. Other problems with the same pattern: Group Anagrams, First Unique Character in a String, Number of Matching Subsequences.

Is there a brute force solution for Minimum Number of Steps to Make Two Strings Anagram?

Yes. Brute force (match letters one by one) takes O(n²) time and O(n) space. For each letter of s, look for an unused equal letter in t and mark it as used.

Which edge cases should I test for Minimum Number of Steps to Make Two Strings Anagram?

The strings are already anagrams (answer 0); No letters in common (answer n); Repeated letters, where only some copies are matched; Single-character strings.