Minimum Number of Steps to Make Two Strings Anagram

You are given two strings `s` and `t` of the same length. In one step you may pick any character of `t` and replace it with any other character. Return the minimum number of steps needed to make `t` an anagram of `s`, meaning `t` holds exactly the same letters with the same counts, in any order.

30:00

Minimum Number of Steps to Make Two Strings Anagram
medium
Free written solution
Topics
Companies

You are given two strings s and t of the same length. In one step you may pick any character of t and replace it with any other character. Return the minimum number of steps needed to make t an anagram of s, meaning t holds exactly the same letters with the same counts, in any order.

Example 1:
Input: {"s":"bab","t":"aba"}
Output: 1
Constraints:
  • 1 <= s.length <= 5 * 10^4

  • s.length == t.length

  • s and t consist of lowercase English letters only.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"bab","t":"aba"}

Make one balance bucket per letter. Letters from s push a bucket up, letters from t push it down, so whatever is left over is the mismatch.

s

counted 0/3 (each adds +1)

b
a
b

t

counted 0/3 (each adds -1)

a
b
a

letter balance: count[c] = (c in s) - (c in t)

s has extra (t must gain these)

a

b

t has extra (these get rewritten)

steps = sum of positive buckets:

waiting

Variables
VariableValue
len(s)3
len(t)3
DepthFunction Call
Stack empty
0/8