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 to Form Target String INPUT String s = "abcd" a b c d String t = "cdab" c d a b k = 2 k = 2 s = "abcd" t = "cdab" k = 2 ALGORITHM STEPS 1 Calculate Chunk Size len(s)/k = 4/2 = 2 2 Split s into k parts s: ["ab", "cd"] ab cd 3 Split t into k parts t: ["cd", "ab"] cd ab 4 Compare sorted parts Sort both: ["ab","cd"] s_parts == t_parts ["ab","cd"] == ["ab","cd"] Freq Map "ab": 1 "cd": 1 Match: OK FINAL RESULT Rearranging s substrings: ab cd cd ab = t Output: true Substrings can be rearranged to form t OK - Valid Key Insight: Split both strings into k equal parts. Sort both lists of substrings and compare. If sorted lists match, rearrangement is possible. Use HashMap for O(n) counting approach. TutorialsPoint - Rearrange K Substrings to Form Target String | Optimal Solution
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