We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Rearrange K Substrings to Form Target String

Number: 3595

Difficulty: Medium

Paid? No

Companies: N/A


Problem Description

Given two anagram strings s and t, and an integer k, determine if it is possible to split s into k equal-sized substrings, then rearrange these substrings (without altering the order of characters inside any substring) so that when concatenated in some order, they form t.


Key Insights

  • Both s and t have identical overall character frequencies since they are anagrams.
  • The only allowed operation is to rearrange contiguous substrings obtained by splitting s into k equal parts.
  • Each substring (from s) cannot be altered internally; thus, to form t, every corresponding segment (block) in t must exactly match one of the rearranged blocks from s.
  • Compare the frequency multiset of the sorted blocks in s and t. A match means t can be obtained by rearranging s’s blocks.

Space and Time Complexity

Time Complexity: O(n log(n/k)) because for each of the k blocks (each of length n/k) we sort the substring.
Space Complexity: O(n) for storing the blocks and frequency maps.


Solution

The solution involves splitting both s and t into k contiguous substrings of equal length. For each substring, we compute a canonical representation (by sorting its characters) so that two substrings are considered equivalent if they consist of the same characters in any order. We then build frequency maps (or counters) for the substrings from s and t. If these frequency maps are equal, it is possible to rearrange s's substrings to form t; otherwise, it isn't. This approach leverages hash tables (or dictionaries/maps) to count the blocks, and sorting of each block provides an effective signature to compare blocks regardless of their internal order.


Code Solutions

import collections

def canFormTarget(s, t, k):
    n = len(s)
    block_size = n // k
    # Create list of sorted blocks for s and t
    s_blocks = [''.join(sorted(s[i:i+block_size])) for i in range(0, n, block_size)]
    t_blocks = [''.join(sorted(t[i:i+block_size])) for i in range(0, n, block_size)]
    # Compare frequency counts of both block lists
    return collections.Counter(s_blocks) == collections.Counter(t_blocks)

# Example usage:
s = "aabbcc"
t = "bbaacc"
k = 3
print(canFormTarget(s, t, k))  # Expected output: True
← Back to All Questions