##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/2287.html

# 2287. Rearrange Characters to Make Target String

• Difficulty: Easy.
• Related Topics: Hash Table, String, Counting.
• Similar Questions: Find Words That Can Be Formed by Characters, Maximum Number of Occurrences of a Substring.

## Problem

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.**

Example 1:

Input: s = "ilovecodingonleetcode", target = "code"
Output: 2
Explanation:
For the first copy of "code", take the letters at indices 4, 5, 6, and 7.
For the second copy of "code", take the letters at indices 17, 18, 19, and 20.
The strings that are formed are "ecod" and "code" which can both be rearranged into "code".
We can make at most two copies of "code", so we return 2.


Example 2:

Input: s = "abcba", target = "abc"
Output: 1
Explanation:
We can make one copy of "abc" by taking the letters at indices 0, 1, and 2.
We can make at most one copy of "abc", so we return 1.
Note that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of "abc".


Example 3:

Input: s = "abbaccaddaeea", target = "aaaaa"
Output: 1
Explanation:
We can make one copy of "aaaaa" by taking the letters at indices 0, 3, 6, 9, and 12.
We can make at most one copy of "aaaaa", so we return 1.


Constraints:

• 1 <= s.length <= 100

• 1 <= target.length <= 10

• s and target consist of lowercase English letters.

## Solution (Java, C++, Python)

• class Solution {
public int rearrangeCharacters(String s, String target) {
return getMaxCopies(target, getCharCount(s), getCharCount(target));
}

private int[] getCharCount(String str) {
int[] charToCount = new int[26];
for (int i = 0; i < str.length(); i++) {
charToCount[str.charAt(i) - 'a']++;
}
return charToCount;
}

private int getMaxCopies(String target, int[] sCount, int[] tCount) {
int copies = Integer.MAX_VALUE;
for (int i = 0; i < target.length(); i++) {
int ch = target.charAt(i) - 'a';
copies = Math.min(copies, sCount[ch] / tCount[ch]);
}
return copies;
}
}

• Todo

• class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
cnt1 = Counter(s)
cnt2 = Counter(target)
return min(cnt1[c] // v for c, v in cnt2.items())

############

# 2287. Rearrange Characters to Make Target String
# https://leetcode.com/problems/rearrange-characters-to-make-target-string/

class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
counter = Counter(s)
tt = Counter(target)

return min(counter[t] // tt[t] for t in tt)



Explain:

nope.

Complexity:

• Time complexity : O(n).
• Space complexity : O(n).