medium Minimum Number of Steps to Make Two Strings Anagram
Problem Statement
Given two strings, s and t, of the same length, return the minimum number of steps required to make t an anagram of s.
In each step, you can replace any character in t with another character.
An anagram of a string is a string that contains the same characters in any order.
Examples
Example 1:
- Input: s = "designgurus", t = "garumdespgn"
- Expected Output: 3
- Justification: We need to replace
a,m, andpcharacters in the stringtto match the frequency of characters ins.
Example 2:
- Input: s = "abc", t = "def"
- Expected Output: 3
- Justification: We need to replace all three characters in
tto match those ins.
Example 3:
- Input: s = "listen", t = "silent"
- Expected Output: 0
- Justification: The string
tis already an anagram ofs.
Constraints:
- 1 <= s.length <= 5 * 104
s.length == t.lengthsandtconsist of lowercase English letters only.
Try it yourself
Try solving this question here:
✅ Solution Minimum Number of Steps to Make Two Strings Anagram
Problem Statement
Given two strings, s and t, of the same length, return the minimum number of steps required to make t an anagram of s.
In each step, you can replace any character in t with another character.
An anagram of a string is a string that contains the same characters in any order.
Examples
Example 1:
- Input: s = "designgurus", t = "garumdespgn"
- Expected Output: 3
- Justification: We need to replace
a,m, andpcharacters in the stringtto match the frequency of characters ins.
Example 2:
- Input: s = "abc", t = "def"
- Expected Output: 3
- Justification: We need to replace all three characters in
tto match those ins.
Example 3:
- Input: s = "listen", t = "silent"
- Expected Output: 0
- Justification: The string
tis already an anagram ofs.
Constraints:
- 1 <= s.length <= 5 * 104
s.length == t.lengthsandtconsist of lowercase English letters only.
Solution
To solve this problem, we use a HashMap to keep track of the frequency differences between the characters in two strings, s and t. The idea is to increment the frequency count for each character in t and decrement it for each character in s. This will give us a map with the net frequency difference for each character. By summing up the positive differences, we can determine the minimum number of steps required to make t an anagram of s.
This method ensures that we efficiently count and compare character frequencies, making the solution both time-efficient and easy to implement.
Step-by-step Algorithm
-
Initialize Frequency Difference Map:
- Create a map to store the frequency difference of characters between the two strings. This map will help track how many characters need to be added or removed to make the strings anagrams of each other.
-
Count the Frequency Differences:
- For each character in the strings
sandt:- Increment the count for the character in
tin the frequency difference map. - Decrement the count for the character in
sin the frequency difference map. - This step helps identify the characters that are in excess or deficit in
tcompared tos.
- Increment the count for the character in
- For each character in the strings
-
Calculate the Number of Steps Needed:
- Initialize a variable
stepsto 0. This will keep track of the number of characters that need to be replaced. - For each count in the frequency difference map:
- If the count is positive, add it to
steps. This represents the characters intthat are in excess and need to be replaced to matchs. In this step, the excess characters of stringswill be replaced by the excess characters of stringt. So, we don't need to count them.
- If the count is positive, add it to
- Initialize a variable
-
Return the Result:
- Return the value of
steps, which represents the minimum number of character replacements needed to maketan anagram ofs.
- Return the value of
Algorithm Walkthrough
Using the input:
- s = "designgurus"
- t = "garumdespgn"
-
Initialization:
frequencyDifference= {}
-
Traverse both strings and update frequency differences:
- i = 0:
charT = 'g',charS = 'd'- Increment frequency of 'g':
frequencyDifference.put('g', 1) - Decrement frequency of 'd':
frequencyDifference.put('d', -1) frequencyDifference= {'g': 1, 'd': -1}
- i = 1:
charT = 'a',charS = 'e'- Increment frequency of 'a':
frequencyDifference.put('a', 1) - Decrement frequency of 'e':
frequencyDifference.put('e', -1) frequencyDifference= {'g': 1, 'd': -1, 'a': 1, 'e': -1}
- i = 2:
charT = 'r',charS = 's'- Increment frequency of 'r':
frequencyDifference.put('r', 1) - Decrement frequency of 's':
frequencyDifference.put('s', -1) frequencyDifference= {'g': 1, 'd': -1, 'a': 1, 'e': -1, 'r': 1, 's': -1}
- i = 3:
charT = 'u',charS = 'i'- Increment frequency of 'u':
frequencyDifference.put('u', 1) - Decrement frequency of 'i':
frequencyDifference.put('i', -1) frequencyDifference= {'g': 1, 'd': -1, 'a': 1, 'e': -1, 'r': 1, 's': -1, 'u': 1, 'i': -1}
- i = 4:
charT = 'm',charS = 'g'- Increment frequency of 'm':
frequencyDifference.put('m', 1) - Decrement frequency of 'g':
frequencyDifference.put('g', 0) frequencyDifference= {'g': 0, 'd': -1, 'a': 1, 'e': -1, 'r': 1, 's': -1, 'u': 1, 'i': -1, 'm': 1}
- i = 5:
charT = 'd',charS = 'n'- Increment frequency of 'd':
frequencyDifference.put('d', 0) - Decrement frequency of 'n':
frequencyDifference.put('n', -1) frequencyDifference= {'g': 0, 'd': 0, 'a': 1, 'e': -1, 'r': 1, 's': -1, 'u': 1, 'i': -1, 'm': 1, 'n': -1}
- i = 6:
charT = 'e',charS = 'g'- Increment frequency of 'e':
frequencyDifference.put('e', 0) - Decrement frequency of 'g':
frequencyDifference.put('g', -1) frequencyDifference= {'g': -1, 'd': 0, 'a': 1, 'e': 0, 'r': 1, 's': -1, 'u': 1, 'i': -1, 'm': 1, 'n': -1}
- i = 7:
charT = 's',charS = 'u'- Increment frequency of 's':
frequencyDifference.put('s', 0) - Decrement frequency of 'u':
frequencyDifference.put('u', 0) frequencyDifference= {'g': -1, 'd': 0, 'a': 1, 'e': 0, 'r': 1, 's': 0, 'u': 0, 'i': -1, 'm': 1, 'n': -1}
- i = 8:
charT = 'p',charS = 'r'- Increment frequency of 'p':
frequencyDifference.put('p', 1) - Decrement frequency of 'r':
frequencyDifference.put('r', 0) frequencyDifference= {'g': -1, 'd': 0, 'a': 1, 'e': 0, 'r': 0, 's': 0, 'u': 0, 'i': -1, 'm': 1, 'n': -1, 'p': 1}
- i = 9:
charT = 'g',charS = 'u'- Increment frequency of 'g':
frequencyDifference.put('g', 0) - Decrement frequency of 'u':
frequencyDifference.put('u', -1) frequencyDifference= {'g': 0, 'd': 0, 'a': 1, 'e': 0, 'r': 0, 's': 0, 'u': -1, 'i': -1, 'm': 1, 'n': -1, 'p': 1}
- i = 10:
charT = 'n',charS = 's'- Increment frequency of 'n':
frequencyDifference.put('n', 0) - Decrement frequency of 's':
frequencyDifference.put('s', -1) frequencyDifference= {'g': 0, 'd': 0, 'a': 1, 'e': 0, 'r': 0, 's': -1, 'u': -1, 'i': -1, 'm': 1, 'n': 0, 'p': 1}
- i = 0:
-
Calculate steps:
- Initialize
steps= 0 - Iterate over
frequencyDifferencevalues:- 'g' = 0 -> steps += 0
- 'd' = 0 -> steps += 0
- 'a' = 1 -> steps += 1
- 'e' = 0 -> steps += 0
- 'r' = 0 -> steps += 0
- 's' = -1 -> steps += 0
- 'u' = -1 -> steps += 0
- 'i' = -1 -> steps += 0
- 'm' = 1 -> steps += 1
- 'n' = 0 -> steps += 0
- 'p' = 1 -> steps += 1
- Initialize
-
Return result:
steps= 3
Thus, the minimum number of replacements needed to make "garumdespgn" an anagram of "designgurus" is 3.
Code
import java.util.HashMap;
import java.util.Map;
class Solution {
public int calculateSteps(String s, String t) {
Map<Character, Integer> frequencyDifference = new HashMap<>();
// Count the difference in frequencies of characters between t and s
for (int i = 0; i < s.length(); i++) {
char charT = t.charAt(i);
char charS = s.charAt(i);
frequencyDifference.put(
charT,
frequencyDifference.getOrDefault(charT, 0) + 1
);
frequencyDifference.put(
charS,
frequencyDifference.getOrDefault(charS, 0) - 1
);
}
int steps = 0;
// Calculate the number of steps needed to make t an anagram of s
for (int count : frequencyDifference.values()) {
// Add the positive difference of character counts to steps
// This represents the number of characters to be replaced
if (count > 0) {
steps += count;
}
}
return steps;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.calculateSteps("designgurus", "garumdespgn")); // Output: 4
System.out.println(sol.calculateSteps("abc", "def")); // Output: 3
System.out.println(sol.calculateSteps("listen", "silent")); // Output: 0
}
}
Complexity Analysis
Time Complexity
- The code performs a single loop over the length of the strings
sandt, which is, where nis the length of the strings. - The
HashMapoperations (put and get) are average. - Therefore, the overall time complexity is
.
Space Complexity
- The space complexity is determined by the
HashMap, which stores at most 26 character frequencies, resulting inspace complexity since the number of unique characters is constant.
🤖 Don't fully get this? Learn it with Claude
Stuck on Minimum Number of Steps to Make Two Strings Anagram? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Minimum Number of Steps to Make Two Strings Anagram** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Minimum Number of Steps to Make Two Strings Anagram** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Minimum Number of Steps to Make Two Strings Anagram**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Minimum Number of Steps to Make Two Strings Anagram**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.