Rearrange K Substrings to Form Target String - Problem
Rearrange K Substrings to Form Target String
Imagine you have a string
Your task is to determine if you can:
1. Split string
2. Rearrange these substrings in any order
3. Concatenate them to form the target string
Return
Key Constraints:
• All substrings must be of equal length
• You can only rearrange complete substrings, not individual characters
• The original character frequencies must be preserved
Imagine you have a string
s and need to transform it into a target string t using a specific constraint. Both strings are anagrams of each other (contain the same characters with the same frequencies).Your task is to determine if you can:
1. Split string
s into exactly k equal-sized substrings2. Rearrange these substrings in any order
3. Concatenate them to form the target string
tReturn
true if this transformation is possible, false otherwise.Key Constraints:
• All substrings must be of equal length
• You can only rearrange complete substrings, not individual characters
• The original character frequencies must be preserved
Input & Output
example_1.py — Basic Case
$
Input:
{"s": "abcdef", "t": "cdefab", "k": 3}
›
Output:
true
💡 Note:
We can split 'abcdef' into 3 chunks: ['ab', 'cd', 'ef']. Rearranging as ['cd', 'ef', 'ab'] gives 'cdefab' which matches the target.
example_2.py — Impossible Case
$
Input:
{"s": "abcdef", "t": "acbdef", "k": 2}
›
Output:
false
💡 Note:
Split 'abcdef' into 2 chunks: ['abc', 'def']. Target 'acbdef' would need chunks ['acb', 'def'], but 'acb' ≠ 'abc', so rearrangement is impossible.
example_3.py — Edge Case
$
Input:
{"s": "aabb", "t": "abab", "k": 2}
›
Output:
true
💡 Note:
Split 'aabb' into ['aa', 'bb'] and 'abab' into ['ab', 'ab']. Since we need 2 'ab' chunks but only have 'aa' and 'bb', this should return false. Wait - let me recalculate: we need chunks that can be rearranged, so 'aa','bb' vs 'ab','ab' - these are different, so false.
Constraints
- 1 ≤ s.length ≤ 104
- s.length == t.length
- s.length % k == 0
- 1 ≤ k ≤ s.length
- s and t consist of lowercase English letters only
- s and t are anagrams of each other
Visualization
Tap to expand
Understanding the Visualization
1
Cut into pieces
Split both strings into k equal-sized chunks
2
Count piece types
Create inventory of what pieces you have vs what you need
3
Compare inventories
If inventories match exactly, rearrangement is possible
Key Takeaway
🎯 Key Insight: By comparing frequency maps of k-length chunks from both strings, we can determine in O(n) time whether rearrangement is possible, avoiding the expensive O(k!) brute force approach.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code