LeetCode - Strings - Minimum Number of Steps to Make Two Strings Anagram

Given two equal-size strings 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.


Example 1:

Input: s = "bab", t = "aba"
Output: 1
Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.

Example 2:

Input: s = "leetcode", t = "practice"
Output: 5
Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.
class Solution {
    public int minSteps(String s, String t) {
            return 0;
        char s_sort[] = s.toCharArray();
        String s_sorted = new String(s_sort);
        char t_sort[] = t.toCharArray();
        String t_sorted = new String(t_sort);
            return 0;
        int counter = 0;
        Map<String,Integer> s_map = getFreqMap(s);
        Map<String,Integer> t_map = getFreqMap(t);
        for(String s1: s_map.keySet()){
                if(t_map.get(s1) < s_map.get(s1)){
                    counter = counter + s_map.get(s1) - t_map.get(s1);
                counter = counter + s_map.get(s1);
        return counter;
    public Map<String,Integer> getFreqMap(String s){
        Map<String,Integer> freqMap = new TreeMap<String,Integer>();
        for(char c:s.toCharArray()){
        return freqMap;

Recent Updates

Recent updates on DevOpsPal


Follow us of social for latest updates.

DevOps Hub

Links to get started.