#3365

Rearrange K Substrings to Form Target String

Medium
Hash TableStringSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of generating permutations, we can directly check if the frequency of characters in `s` can be rearranged into `t` by counting the characters in each substring and ensuring they can be grouped correctly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if the length of `s` is divisible by `k`. If not, return false.
  2. 2Step 2: Count the frequency of characters in `s` and `t`.
  3. 3Step 3: For each character, check if its frequency in `s` can be evenly distributed into `k` substrings.
solution.py13 lines
1# Full working Python code
2from collections import Counter
3
4def can_form_target(s, t, k):
5    n = len(s)
6    if n % k != 0:
7        return False
8    count_s = Counter(s)
9    count_t = Counter(t)
10    for char in count_s:
11        if count_s[char] % k != 0 or count_s[char] != count_t[char]:
12            return False
13    return True

Complexity note: The time complexity is O(n) because we only traverse the strings a couple of times to count character frequencies, which is efficient compared to generating permutations.

  • 1Both strings must be anagrams, ensuring they contain the same characters.
  • 2The length of `s` must be divisible by `k` to split into equal substrings.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.