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 Anagram INPUT String s = "bab" b a b 0 1 2 String t = "aba" a b a 0 1 2 s: a=1, b=2 t: a=2, b=1 s="bab", t="aba" ALGORITHM STEPS 1 Create count array[26] Track char differences 2 Single pass: s and t count[s[i]]++, count[t[i]]-- 3 Process each index i=0: count[b]++, count[a]-- 4 Sum positive values = chars needed to change Count Array (after processing): -1 a +1 b 0 c-z Sum of positives: 1 FINAL RESULT Before: a b a After (1 step): b a b changed! Changed 'a' --> 'b' Now t="bab" is anagram of s Output: 1 Key Insight: Single pass optimization: Increment count for s[i] and decrement for t[i] simultaneously. Positive values show excess chars in s (chars t needs). Sum of positives = minimum replacements needed. TutorialsPoint - Minimum Number of Steps to Make Two Strings Anagram | Single Pass Optimized Time: O(n) | Space: O(1) - fixed 26 character array
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