Minimum Number of Steps to Make Two Strings Anagram - Problem

You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.

Return the minimum number of steps to make t an anagram of s.

An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.

Input & Output

Example 1 — Basic Case
$ Input: s = "bab", t = "aba"
Output: 1
💡 Note: String t has 2 'a's but s only has 1 'a'. Replace one 'a' in t with 'b' to make "bab" or "bba"
Example 2 — Multiple Changes
$ Input: s = "leetcode", t = "practice"
Output: 5
💡 Note: t needs to be transformed: 'p'→'l', 'r'→'e', 'a'→'e', 'i'→'t', 'c' remains, so 5 changes needed
Example 3 — Already Anagram
$ Input: s = "anagram", t = "mangaar"
Output: 0
💡 Note: Both strings already have same character frequencies, no changes needed

Constraints

  • 1 ≤ s.length ≤ 5 × 104
  • s.length == t.length
  • s and t consist of lowercase English letters only

Visualization

Tap to expand
Minimum Steps to Make Two Strings Anagrams = "bab"babt = "aba"abaCharacter Count Analysis:s: a=1, b=2t: a=2, b=1Excess in t: a has 1 extraReplaceMinimum Steps: 1Transform "aba" → "bab" or "bba" with 1 replacement
Understanding the Visualization
1
Input Analysis
Two equal-length strings s and t
2
Frequency Count
Count character occurrences in both strings
3
Calculate Steps
Count excess characters in t that need replacement
Key Takeaway
🎯 Key Insight: Count excess characters in t compared to s - those are the minimum replacements needed
Asked in
Facebook 15 Amazon 12 Microsoft 8
89.4K Views
Medium Frequency
~15 min Avg. Time
1.8K 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