Minimum Number of Steps to Make Two Strings Anagram - Problem

You're given two strings s and t of equal length. Your goal is to transform string t into an anagram of string s by replacing characters in t.

In each step, you can choose any character in t and replace it with any other character. An anagram contains the same characters with the same frequencies, but possibly in different positions.

Example: If s = "bab" and t = "aba", they're already anagrams, so 0 steps are needed. If s = "leetcode" and t = "practice", we need to replace some characters in t to match the character frequencies of s.

Return the minimum number of character replacements needed to make t an anagram of s.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "bab", t = "aba"
โ€บ Output: 1
๐Ÿ’ก Note: Replace the first 'a' in t with 'b': "aba" โ†’ "bba" (which is an anagram of "bab"). Only 1 step needed.
example_2.py โ€” Complex Case
$ Input: s = "leetcode", t = "practice"
โ€บ Output: 5
๐Ÿ’ก Note: s has letters {l:1, e:3, t:1, c:1, o:1, d:1}. t has {p:1, r:1, a:1, c:1, t:1, i:1, e:1}. We need to replace p, r, a, i, and one extra consonant to match s's frequencies.
example_3.py โ€” Already Anagram
$ Input: s = "anagram", t = "nagaram"
โ€บ Output: 0
๐Ÿ’ก Note: The strings are already anagrams of each other, so no replacements are needed.

Visualization

Tap to expand
Anagram Step CalculationString s (Target)"leetcode"String t (Current)"practice"Frequency Count (s)l: 1e: 3t: 1c: 1o: 1d: 1Frequency Count (t)p: 1r: 1a: 1c: 1t: 1i: 1e: 1Characters to Replacep, r, a, i, (e excess)Answer: 5
Understanding the Visualization
1
Count Differences
Track what you need (+) vs what you have (-)
2
Find Excess
Identify characters that appear more in t than in s
3
Calculate Steps
Sum up all the excess characters to get minimum replacements
Key Takeaway
๐ŸŽฏ Key Insight: Count character frequency differences in one pass. The sum of positive differences equals the minimum replacements needed.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through both strings of length n

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Hash map stores at most 26 characters (constant space)

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s.length โ‰ค 5 ร— 104
  • s.length == t.length
  • s and t consist of lowercase English letters only
  • Both strings have the same length
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
89.0K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen