Rearrange Characters to Make Target String

Rearrange Characters to Make Target String

You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings.

Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them.

LeetCode Problem - 2287

class Solution {
    public int rearrangeCharacters(String s, String target) {
        // Create a map to store the frequency of characters in string s
        Map<Character, Integer> map = new HashMap<>();
        for (char ch : s.toCharArray()) {
            map.put(ch, map.getOrDefault(ch, 0) + 1); // Increment the count for each character in s
        }

        // Create a map to store the frequency of characters in string target
        Map<Character, Integer> map2 = new HashMap<>();
        for (char ch : target.toCharArray()) {
            map2.put(ch, map2.getOrDefault(ch, 0) + 1); // Increment the count for each character in target
        }

        // Initialize the minimum number of times the target string can be formed
        int min = Integer.MAX_VALUE;

        // Iterate through each character in the target string
        for (char ch : target.toCharArray()) {
            try {
                // Get the count of character ch in both strings
                int val1 = map.get(ch);   // Frequency of ch in s
                int val2 = map2.get(ch);  // Frequency of ch in target

                // Calculate how many times the character can be used to form the target
                min = Math.min(min, val1 / val2);
            } catch (Exception e) {
                // If the character from target is not found in s, return 0
                return 0;
            }
        }

        // Return the minimum value found, which represents how many times target can be formed
        return min;
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!