Leetcode : 1347 – Minimum number of steps to make two strings anagram

Algorithm

  1. Initialize an array count of size 26,
  2. Set all indices point to 0 initially
  3. Iterate over the integer from 0 to the last index in s or t, for each index i:
    1. Increment the frequency of character t[i] in the array count.
    2. Decerement the frequency of character s[i] in the array count.
  4. Initialize the variable ans to 0
  5. Iterate over the integers from 0 to 25, and for each positive frequency difference, add it to the variable ans.
  6. Return ans.

Java

public int minSteps(String s, String t) {
        int[] count = new int[26];
       
        for (int i = 0; i < s.length(); i++) {
            count[t.charAt(i) - 'a']++;
            count[s.charAt(i) - 'a']--;
        }

        int ans = 0;
        for (int i = 0; i < 26; i++) {
            ans += Math.max(0, count[i]);
        }

        return ans;
    }

Python

def minSteps(self, s: str, t: str) -> int:
        cnt1 = Counter(s)
        cnt2 = Counter(t)
        res = 0
        for c in ascii_lowercase:
            if cnt2[c] > cnt1[c]:
                res += cnt2[c] - cnt1[c]
        return res

Leave a comment