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 to Make Target String INPUT Source String s: i l o v e c o d i n g o n l e e t c o d e Target String: c o d e Frequency in s: c: 2 o: 4 d: 2 e: 4 i: 2 l: 2 n: 2 g: 1 t: 1 Frequency in target: c: 1 o: 1 d: 1 e: 1 ALGORITHM STEPS 1 Count chars in s Build frequency map 2 Count chars in target Build frequency map 3 Calculate ratios s[char] / target[char] 4 Find minimum ratio Bottleneck character Ratio Calculation: c: 2/1 = 2 o: 4/1 = 4 d: 2/1 = 2 [MIN] e: 4/1 = 4 min(2, 4, 2, 4) = 2 FINAL RESULT We can form 2 copies of "code": Copy 1 c o d e Copy 2 c o d e Output: 2 Remaining unused: i,l,o,v,i,n,g,o,n,l,e,e,t [OK] Verified Key Insight: The bottleneck character determines the maximum copies. For each char in target, calculate how many times it appears in s divided by how many times it's needed in target. The minimum ratio across all target chars gives the answer. Time: O(n+m), Space: O(1) TutorialsPoint - Rearrange Characters to Make Target String | Optimal Solution
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