Minimum Number of Steps to Make Two Strings Anagram
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^4s.length == t.lengthsandtcontain 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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| 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)
O(n²)Each of the n letters of s may scan all of t.O(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.
- used = boolean array over t, steps = 0.
- For each character c of s, scan t for an index j with t[j] == c and not used[j].
- If found, mark used[j]; otherwise steps++.
- 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;
}
}class Solution:
def minSteps(self, s: str, t: str) -> int:
n = len(t)
used = [False] * n
steps = 0
for c in s:
found = False
for j in range(n):
if not used[j] and t[j] == c:
used[j] = True
found = True
break
if not found:
steps += 1
return stepsclass Solution {
public:
int minSteps(string s, string t) {
int n = t.size(), steps = 0;
vector<bool> used(n, false);
for (char c : s) {
bool found = false;
for (int j = 0; j < n; j++) {
if (!used[j] && t[j] == c) {
used[j] = true;
found = true;
break;
}
}
if (!found) steps++;
}
return steps;
}
};function minSteps(s, t) {
const n = t.length;
const used = new Array(n).fill(false);
let steps = 0;
for (const c of s) {
let found = false;
for (let j = 0; j < n; j++) {
if (!used[j] && t[j] === c) {
used[j] = true;
found = true;
break;
}
}
if (!found) steps++;
}
return steps;
}2Optimal (letter counts)
O(n)One pass over both strings plus 26 counters.O(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.
- count[26] = 0. For each i: count[s[i] - 'a']++, count[t[i] - 'a']--.
- 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;
}
}class Solution:
def minSteps(self, s: str, t: str) -> int:
count = [0] * 26
for a, b in zip(s, t):
count[ord(a) - 97] += 1
count[ord(b) - 97] -= 1
return sum(c for c in count if c > 0)class Solution {
public:
int minSteps(string s, string t) {
int count[26] = {0};
for (int i = 0; i < (int)s.size(); i++) {
count[s[i] - 'a']++;
count[t[i] - 'a']--;
}
int steps = 0;
for (int c : count) {
if (c > 0) steps += c;
}
return steps;
}
};function minSteps(s, t) {
const count = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
count[s.charCodeAt(i) - 97]++;
count[t.charCodeAt(i) - 97]--;
}
let steps = 0;
for (const c of 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.