LeetCode 1347: Minimum Number of Steps to Make Two Strings Anagram Solution

Master LeetCode problem 1347 (Minimum Number of Steps to Make Two Strings Anagram), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1347. Minimum Number of Steps to Make Two Strings Anagram

Problem Explanation

Explanation

To solve this problem, we need to find the minimum number of steps required to make two strings s and t anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

We can approach this problem by counting the frequency of each character in both strings and then calculating the difference in frequencies for each character. The sum of these differences will give us the minimum number of steps required to make t an anagram of s.

  1. Create two arrays countS and countT of size 26 to store the frequency of each character in strings s and t, respectively.
  2. Iterate over both strings simultaneously and update the frequencies in the respective arrays.
  3. Calculate the difference in frequencies for each character and accumulate the absolute differences.
  4. Return the total accumulated differences as the result.

Time Complexity:

  • The time complexity of this solution is O(n), where n is the length of strings s and t.

Space Complexity:

  • The space complexity is O(1) as we are using constant space (arrays of size 26 for counting frequencies).

Solution Code

public int minSteps(String s, String t) {
    int[] countS = new int[26];
    int[] countT = new int[26];

    for (char c : s.toCharArray()) {
        countS[c - 'a']++;
    }

    for (char c : t.toCharArray()) {
        countT[c - 'a']++;
    }

    int steps = 0;
    for (int i = 0; i < 26; i++) {
        steps += Math.abs(countS[i] - countT[i]);
    }

    return steps;
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1347 (Minimum Number of Steps to Make Two Strings Anagram)?

This page provides optimized solutions for LeetCode problem 1347 (Minimum Number of Steps to Make Two Strings Anagram) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1347 (Minimum Number of Steps to Make Two Strings Anagram)?

The time complexity for LeetCode 1347 (Minimum Number of Steps to Make Two Strings Anagram) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1347 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1347 in Java, C++, or Python.

Back to LeetCode Solutions