Minimum Number of Steps to Make Two Strings Anagram

Problem Id: 1347 Difficulty: Medium Tag: String


Intuition

String s1 is anagram with s2 if and only if they have the same number of each letters. So we could calculate how many differences are there in the count of each letters. One change would reduce 2 differences, so we could get the total number of change by only adding the negative difference.

Solution


from collections import defaultdict


class Solution:
    def minSteps(self, s: str, t: str) -> int:
        count = defaultdict(int)
        for c in s:
            count[c] += 1
        for c in t:
            count[c] -= 1
        steps = 0
        for v in count.values():
            if v > 0:
                steps += v
        return steps