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
Rearrange Characters: Maximum Target CopiesInput:s = "ilovecodingonleetcode"target = "code"Character Analysis:c: 2÷1=2o: 4÷1=4d: 2÷1=2e: 4÷1=4Process:1. Count frequencies: s has c:2, o:4, d:2, e:42. Target needs: c:1, o:1, d:1, e:13. Calculate ratios: 2/1, 4/1, 2/1, 4/14. Minimum ratio determines answerOutput: 2 (limited by characters c and d)
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
Asked in
Google 15 Amazon 12 Microsoft 8
23.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen