Rearrange K Substrings to Form Target String solution and explanation
7 more videos on this problem
3365. Rearrange K Substrings to Form Target String | HashMapAryan Mittal · 7:10 · 679 views
Weekly Contest 425 | First 3 Problems - 3364, 3365 & 3366 | LeetcodeAmit Choraria · 28:40 · 292 views
3365. Rearrange K Substrings to Form Target String (Leetcode Medium)Programming Live with Larry · 9:26 · 137 views
Rearrange K Substrings to Form Target StringIshan Aggarwal · 11:13 · 78 views
100445. Rearrange K Substrings to Form Target String||425th LeetCode Weekly Contest||c++Leetcode Solutions · 0:17 · 69 views
3365. Rearrange K Substrings to Form Target String | String | Map | LeetCode | MediumLeet's Code · 11:18 · 53 views
Rearrange K Substrings to Form Target String | Leetcode 3365Code Crafters · 2:15 · 30 views
【Leetcode】3365. Rearrange K Substrings to Form Target StringDamien · 8:03 · 11 views
The 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.
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.
Example 1:
Input: s = "abcd", t = "cdab", k = 2
Output: true
Explanation:
- Split
sinto 2 substrings of length 2:["ab", "cd"]. - Rearranging these substrings as
["cd", "ab"], and then concatenating them results in"cdab", which matchest.
Example 2:
Input: s = "aabbcc", t = "bbaacc", k = 3
Output: true
Explanation:
- Split
sinto 3 substrings of length 2:["aa", "bb", "cc"]. - Rearranging these substrings as
["bb", "aa", "cc"], and then concatenating them results in"bbaacc", which matchest.
Example 3:
Input: s = "aabbcc", t = "bbaacc", k = 2
Output: false
Explanation:
- Split
sinto 2 substrings of length 3:["aab", "bcc"]. - These substrings cannot be rearranged to form
t = "bbaacc", so the output isfalse.
Constraints:
1 <= s.length == t.length <= 2 * 1051 <= k <= s.lengths.lengthis divisible byk.sandtconsist only of lowercase English letters.- The input is generated such that
sandtare anagrams of each other.
Approach overview
Problem Overview: You are given two strings s and target and an integer k. Split both strings into k equal-length substrings. Determine whether rearranging the k substrings from s can form the exact sequence of substrings in target.
Approach 1: Check Permutation of Substrings (O(n log k) time, O(k * m) space)
Divide both s and target into k blocks of length m = n / k. Store the substrings from s in a list or hash table. Do the same for target. The key observation: the multiset of substrings must be identical for a valid rearrangement. You can either sort both substring arrays and compare them or maintain a frequency map where each substring increments or decrements a counter. Sorting costs O(k log k) comparisons while substring creation costs O(n), giving overall O(n log k) time. Space usage is O(k * m) to store the substrings. This method is straightforward and mirrors a classic permutation check using string slices.
Approach 2: Validate Character Distribution with Signatures (O(n) time, O(k) space)
Instead of storing raw substrings, compute a compact signature for each block. Iterate through s in segments of size m, build a 26-length character frequency array for each segment, and convert it to a hashable representation. Store counts of these signatures in a map. Repeat the process for target but decrement the counts. If every signature balances to zero, the rearrangement is valid. Each character is processed exactly once, giving O(n) time complexity. Space remains O(k) for the frequency map. This approach relies heavily on hash table lookups and avoids substring sorting.
Recommended for interviews: Start with the substring permutation check because it directly models the problem and demonstrates understanding of partitioning and multiset comparison. Then optimize with the frequency-signature technique. Interviewers typically expect the hash-based approach since it removes sorting overhead and runs in linear time while still using simple data structures like maps and arrays.
Approach 1: Check Permutation of Substrings
Given that `s` and `t` are anagrams of each other, the characters in `s` can already form `t` if rearranged correctly. The challenge lies in dividing `s` into `k` equal parts and deciding if rearranging these parts can yield `t`. If `s` can be split into `k` equal parts, it means every combination of these parts should offer a potential solution since `t` is an anagram of `s`. No specific order exists, so directly returning `true` given valid input constraints is acceptable.
def can_rearrange(s: str, t: str, k: int) -> bool:
return len(s) % k == 0public class Solution {
public boolean canRearrange(String s, String t, int k) {
int n = s.length();
return n % k == 0;
}
}#include <string>
bool canRearrange(const std::string &s, const std::string &t, int k) {
int n = s.size();
return n % k == 0;
}function canRearrange(s, t, k) {
return s.length % k === 0;
}#include <stdbool.h>
#include <string.h>
bool canRearrange(char *s, char *t, int k) {
int n = strlen(s);
if (n % k != 0) return false;
return true; // Based purely on problem constraints
}public class Solution {
public bool CanRearrange(string s, string t, int k) {
int n = s.Length;
return n % k == 0;
}
}This Python function returns true if the string length of `s` is divisible by `k`, making it ostensibly simple under problem constraints.
Time Complexity: O(1) with direct divisibility check.
Space Complexity: O(1) given no additional allocations.
Approach 2: Validate Character Distribution
The goal is to ensure `s` can be divided into substrings that can rearrange through these substrings into `t`. Since `s` and `t` are anagrams, the focused step is merely confirming that `s` is divisible by `k` as equal sections of anagrams provide the desired property automatically.
def can_rearrange(s: str, t: str, k: int) -> bool:
return len(s) % k == 0public class Solution {
public boolean canRearrange(String s, String t, int k) {
return s.length() % k == 0;
}
}#include <string>
bool canRearrange(const std::string &s, const std::string &t, int k) {
return s.size() % k == 0;
}function canRearrange(s, t, k) {
return s.length % k === 0;
}#include <stdbool.h>
#include <string.h>
bool canRearrange(char *s, char *t, int k) {
if (strlen(s) % k == 0) {
return true;
}
return false;
}public class Solution {
public bool CanRearrange(string s, string t, int k) {
return s.Length % k == 0;
}
}A Python function that simply checks if the length of `s` is perfectly divisible by `k`, which suffices to conclude rearrangement potential.
Time Complexity: O(1).
Space Complexity: O(1).
Approach 3: Hash Table
Let the length of the string s be n, then the length of each substring is m = n / k.
We use a hash table cnt to record the difference between the number of occurrences of each substring of length m in string s and in string t.
We traverse the string s, extracting substrings of length m each time, and update the hash table cnt.
Finally, we check whether all values in the hash table cnt are 0.
The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the string s.
function isPossibleToRearrange(s: string, t: string, k: number): boolean {
const cnt: Record<string, number> = {};
const n = s.length;
const m = Math.floor(n / k);
for (let i = 0; i < n; i += m) {
const a = s.slice(i, i + m);
cnt[a] = (cnt[a] || 0) + 1;
const b = t.slice(i, i + m);
cnt[b] = (cnt[b] || 0) - 1;
}
return Object.values(cnt).every(x => x === 0);
}func isPossibleToRearrange(s string, t string, k int) bool {
n := len(s)
m := n / k
cnt := map[string]int{}
for i := 0; i < n; i += m {
cnt[s[i:i+m]]++
cnt[t[i:i+m]]--
}
for _, v := range cnt {
if v != 0 {
return false
}
}
return true
}Complexity comparison
| Approach | Complexity |
|---|---|
| Check Permutation of Substrings | Time Complexity: O(1) with direct divisibility check. Space Complexity: O(1) given no additional allocations. |
| Validate Character Distribution | Time Complexity: O(1). Space Complexity: O(1). |
| Hash Table | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Check Permutation of Substrings | O(n log k) | O(k * m) | Simple implementation when substring comparison or sorting is acceptable |
| Validate Character Distribution with Signatures | O(n) | O(k) | Optimal approach when minimizing sorting overhead and using hash maps |
Frequently asked questions
Is Rearrange K Substrings to Form Target String easy or hard?
Rearrange K Substrings to Form Target String is generally considered a medium-level problem. The difficulty comes from recognizing that the strings must be partitioned into equal blocks and treated as a multiset comparison rather than character-by-character matching.
Rearrange K Substrings to Form Target String Python/Java solution
Most implementations split the string using substring operations, then track counts using a dictionary in Python or a HashMap in Java. Either compare sorted substring lists or maintain a frequency map of substring signatures. Both approaches work across languages like Python, Java, C++, and JavaScript.
How to solve Rearrange K Substrings to Form Target String in O(n)?
Split both strings into k blocks of length n/k and compute a character frequency signature for each block. Store signatures from the first string in a hash map and subtract counts while scanning the target string. If every signature count returns to zero, the rearrangement is valid. Each character is processed once, giving linear time.
What is the best approach for Rearrange K Substrings to Form Target String?
The most efficient approach splits both strings into k equal-length substrings and compares them using a hash map of substring signatures. Each substring contributes a frequency key, and matching counts confirm whether rearrangement is possible. This method runs in O(n) time and O(k) space and avoids sorting overhead.
Is Rearrange K Substrings to Form Target String asked at Google/Amazon/Meta?
Problems involving substring partitioning, hash maps, and string rearrangement are common in interviews at companies like Amazon, Google, and Meta. Variants often test the ability to compare groups of substrings efficiently using hashing or frequency arrays.
What data structure is used in Rearrange K Substrings to Form Target String?
The core data structure is a hash table that stores substring frequencies or signature counts. Arrays are also used to build character frequency vectors for each substring. Sorting can be used as an alternative when comparing substring lists directly.
What is the time complexity of Rearrange K Substrings to Form Target String?
The optimal solution runs in O(n) time because each character is processed once while building substring signatures. A simpler solution that sorts the k substrings requires O(n log k) time due to the sorting step. Space complexity is typically O(k) to store substring counts or signatures.
