Rearrange K Substrings to Form Target String - Problem

You are given two strings s and t, both of which are anagrams of each other, and an integer k.

Your task is to determine whether it is possible to split the string s into k equal-sized substrings, rearrange the substrings, and concatenate them in any order to create a new string that matches the given string t.

Return true if this is possible, otherwise, return false.

Note: An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once. A substring is a contiguous non-empty sequence of characters within a string.

Input & Output

Example 1 — Basic Rearrangement
$ Input: s = "abcd", t = "cdab", k = 2
Output: true
💡 Note: Split s into ["ab", "cd"] and t into ["cd", "ab"] with k=2. We can rearrange s chunks ["ab", "cd"] to ["cd", "ab"] to form t.
Example 2 — Impossible Rearrangement
$ Input: s = "abcd", t = "acbd", k = 2
Output: false
💡 Note: Split s into ["ab", "cd"] and t into ["ac", "bd"] with k=2. No rearrangement of s chunks can form t chunks.
Example 3 — Single Character Chunks
$ Input: s = "abc", t = "bca", k = 3
Output: true
💡 Note: Split s into ["a", "b", "c"] and t into ["b", "c", "a"] with k=3. We can rearrange s chunks to match t chunks.

Constraints

  • 1 ≤ s.length, t.length ≤ 1000
  • 1 ≤ k ≤ s.length
  • s.length is divisible by k
  • s and t consist of lowercase English letters only
  • s and t are anagrams of each other

Visualization

Tap to expand
Rearrange K Substrings ProblemInput: s = "abcd", t = "cdab", k = 2s = "abcd"t = "cdab"Split into k=2 parts:"ab""cd"Split into k=2 parts:"cd""ab"Same multiset: {"ab", "cd"} = {"cd", "ab"}✓ Rearrangement possible: return true
Understanding the Visualization
1
Input
Two anagram strings s and t, and integer k
2
Split
Divide both strings into k equal-length substrings
3
Check
Verify if substring multisets match
Key Takeaway
🎯 Key Insight: If k substrings from s can be rearranged to form t, both strings must have identical multisets of k-length substrings
Asked in
Google 25 Microsoft 20 Amazon 15
28.4K Views
Medium Frequency
~15 min Avg. Time
890 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