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:
🎯 STRICT STANDOUT — Minimum Number of Steps to Make Two Strings Anagram — problem
1. Why / judgment
Same length → only replacements. Each replace fixes one excess character in t toward a deficit relative to s. Answer = half the L1 distance of freq vectors = sum of positive (count_t − count_s). Judgment: pure counting; sorting both strings and comparing is O(n log n) and still needs a second pass for replacements count.
2. Big-O derivation (K11)
n ≤ 5e4 lowercase → int[26].
Build both counts O(n); sum max(0, ct−cs) over 26 → O(1).
Total O(n). Space O(1).
designgurus vs garumdespgn → 3.
3. Pattern + when-NOT (K12)
Name: FREQUENCY DIFF / ANAGRAM DISTANCE
Recognition: make anagrams by replace-only; equal lengths.
When-NOT: Different lengths + insert/delete → edit distance / anagram steps variant. Unicode huge alphabet → map not [26]. Need actual mapping of which chars change → reconstruct from diffs.
4. Edge hand-run (K13)
s=t → 0.
s=abc t=def → 3.
s=aab t=abb → 1 (change one b→a or a→b depending side).
5. Interviewer follow-ups (model answers)
Q1. Why sum only positive diffs?
A: Each excess in t must be replaced; deficits are the other side of the same replacements — counting both double-counts.
Q2. Is answer always ≤ n?
A: Yes; at most every char of t replaced.
Q3. Sort both and count mismatches?
A: Wrong: sorted mismatch count is not the replacement distance for anagrams in general — use freqs.
6. Short drills
Drill: listen/silent → 0.
Drill: prove sum positives = (1/2) Σ |cs−ct|.
✅ 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.
🎯 STRICT STANDOUT — Solution Minimum Number of Steps to Make Two Strings Anagram
1. Why / judgment
One array: for each i, diff[t[i]-'a']++, diff[s[i]-'a']--. Sum max(0,diff[c]). Equivalent to separate counters. Prefer single array for cache locality.
2. Big-O derivation (K11)
O(n) char visits + O(26) fold.
Trace s=abc t=def:
a-1 b-1 c-1 d+1 e+1 f+1 → positives 1+1+1=3 ✓
listen/silent: all zero → 0 ✓
designgurus/garumdespgn → 3 ✓
3. Pattern + when-NOT (K12)
Name: CHAR HISTOGRAM DIFF
Recognition: equal-length anagram-by-replace.
When-NOT: Case-sensitive / non-letters → expand alphabet handling.
4. Edge hand-run (K13)
All 'a's vs all 'b's length n → answer n.
One char differ: abcd vs abce → 1.
5. Interviewer follow-ups (model answers)
Q1. Map vs [26]?
A: [26] is O(1) space and faster; map only if alphabet unknown.
Q2. Streaming one string first?
A: Count s fully, then stream t decrementing; count how many t chars go negative / missing — same O(n).
Q3. Why not Levenshtein?
A: Only replace, fixed length → frequency L1/2, not full edit DP O(n²).
6. Short drills
Drill: s=leetcode t=practice → compute 5.
Drill: implement half-L1 form and match.
Recognize it: Membership / frequency / “have I seen this?” in O(1) → a hash map or set.
▶ Visualize this problem (step it, predict each fork)
🤖 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.