Skip to main content
Back to problems
#3365
Medium Algorithms

Rearrange k substrings to form target string

Hash Table String Sorting
56.7% acceptance
Feb 24, 2026
87
7
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;

impl Solution {
  pub fn is_possible_to_rearrange(s: String, t: String, k: i32) -> bool {
    let n = s.len();
    let chunk = n / k as usize;
    // Split s into k chunks, count multiset of chunks
    // Split t into k chunks, count multiset of chunks
    // Check if multisets are equal
    let mut s_map: HashMap<&str, i32> = HashMap::new();
    let mut t_map: HashMap<&str, i32> = HashMap::new();
    let sb = s.as_bytes();
    let tb = t.as_bytes();
    // Need string slices - convert back
    let s_str = &s;
    let t_str = &t;
    for i in (0..n).step_by(chunk) {
      *s_map.entry(&s_str[i..i+chunk]).or_insert(0) += 1;
      *t_map.entry(&t_str[i..i+chunk]).or_insert(0) += 1;
    }
    let _ = (sb, tb); // suppress warning
    s_map == t_map
  }
}