Code Logo

Minimum Steps to Make Two Strings Anagram

Published at23 Jul 2026
Easy 0 views
Like0

Given two equal-length strings, count the minimum steps to make t an anagram of s. In one step, you can change any character of t to any other character. Count the total excess characters in one string over the other and divide by 2.

This is a hash map frequency counting problem: count each character in both strings, sum the absolute differences, and divide by 2. Each excess character in one string needs to be changed to match the deficiency in the other.

This problem is a variant of the classic Valid Anagram problem and tests understanding of frequency difference calculations. The answer is always half the sum of absolute differences because each change fixes one excess in one string and one deficiency in the other.

Edge cases include identical strings (0 steps needed), completely different strings (n steps where n is the length), and single-character strings (0 if same, 1 if different). The frequency difference approach works for all cases.

This problem extends the concept of anagram checking by quantifying how far apart two strings are. The hash map approach naturally computes the per-character difference. Dividing by 2 accounts for the fact that each change reduces the difference for both strings simultaneously.

Example Input & Output

Example 1
Input
"leetcode", "practice"
Output
5
Explanation

5 changes.

Example 2
Input
"anagram", "nagaram"
Output
0
Explanation

Already anagrams.

Example 3
Input
"bab", "aba"
Output
1
Explanation

Change a to b.

Algorithm Flow

Recommendation Algorithm Flow for Minimum Steps to Make Two Strings Anagram
Recommendation Algorithm Flow for Minimum Steps to Make Two Strings Anagram

Solution Approach

Count frequencies in s, decrement for t. Sum absolute values of counts and divide by 2.

function solution(s, t) {
  var counts = {};
  for (var i = 0; i < s.length; i++) counts[s[i]] = (counts[s[i]] || 0) + 1;
  for (var i = 0; i < t.length; i++) counts[t[i]] = (counts[t[i]] || 0) - 1;
  var steps = 0;
  for (var k in counts) steps += Math.abs(counts[k]);
  return Math.trunc(steps / 2);
}

Time O(n), Space O(1).

Best Answers

java
import java.util.*;
class Solution {
    public int solution(String s, String t) {
        int[] counts = new int[26];
        for (char ch : s.toCharArray()) counts[ch-'a']++;
        for (char ch : t.toCharArray()) counts[ch-'a']--;
        int steps = 0;
        for (int c : counts) steps += Math.abs(c);
        return steps/2;
    }
}