Rearrange Characters to Make Target String - 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.
Note: Each character from s can only be used once across all copies of target.
Input & Output
Example 1 — Basic Case
$
Input:
s = "ilovecodingonleetcode", target = "code"
›
Output:
2
💡 Note:
We can form "code" twice: first using c,o,d,e from positions, then using remaining c,o,d,e. Characters c and d each appear twice in s, limiting us to 2 copies.
Example 2 — Limited by One Character
$
Input:
s = "abcba", target = "abc"
›
Output:
1
💡 Note:
s has a:2, b:2, c:1. Target needs a:1, b:1, c:1. Character 'c' appears only once in s, so we can form "abc" only 1 time.
Example 3 — Missing Character
$
Input:
s = "abbaccaddaeea", target = "aaaaa"
›
Output:
1
💡 Note:
s has 5 'a' characters and target needs 5 'a' characters, so we can form "aaaaa" exactly 1 time.
Constraints
- 1 ≤ s.length ≤ 104
- 1 ≤ target.length ≤ 104
- s and target consist of lowercase English letters.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Source string s and target pattern to form
2
Count
Count frequency of each character in both strings
3
Calculate
Find minimum ratio of available/needed for each character
Key Takeaway
🎯 Key Insight: The character with the smallest available/needed ratio determines the maximum number of target copies possible
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code